liveBook · Manning

Global scope

As explained in Secrets of the JavaScript Ninja, Third Edition

The global scope is the outermost JavaScript scope whose bindings are available across a script or execution environment.

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

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains accidental global creation, strict-mode rejection, module scope, and intentional globalThis attachment; stops short of engine internals.
Examples
Uses an undeclared assignment, a strict-mode error, and globalThis.ninjaName shared across modules.
What you can do after
Apply it by attaching a value to globalThis and accessing it across modules.
How it connects
Connects global scope to modules, strict mode, globalThis, and variable declarations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.