Global scope is JavaScript’s outermost scope, represented by properties of globalThis. A value attached there can be referenced by name or through globalThis, including from other modules. section 7.4
Keep these distinctions in mind:
- In older code, assigning to an undeclared name could create a global accidentally; strict mode rejects that assignment. section 7.4
- In modules, top-level declarations belong to the module scope. To share a value globally, attach it to globalThis. section 7.4
Listing 7.7 Attaching a value to the global object
// In globals.mts
declare global { #A
var ninjaName: string; #A
} #A
globalThis.ninjaName = "Naruto"; #B
// In main.mts
import "./globals.mts"; #C
console.log(`It's me, ${ninjaName}!`);
This example declares a global name, assigns it through globalThis, then accesses it from an importing module. section 7.4
