liveBook · Manning

Global object

As explained in Secrets of the JavaScript Ninja, Third Edition

The top-level object that provides globally accessible bindings for a JavaScript execution environment.

The global object is the runtime object through which globally accessible values can be shared. In modern JavaScript, a module’s top-level scope is not global scope, so attach a value to the global object when other modules must access it without importing it. 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}!`);

The declaration makes the global property available to TypeScript; the assignment creates it, allowing the importing module to use the name directly. section 7.4

Use `globalThis` to refer to the global object across environments. It was standardized in ECMAScript 2020; in browsers it equals `window`, and in Node.js it equals `global`. section 7.4

Avoid assuming that an undeclared assignment safely creates a global:

  • In strict mode, assigning to an undeclared name throws a `ReferenceError`. section 7.4
  • Without strict mode, such an assignment can create a global or overwrite an existing global property. section 7.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains global assignment, module scope, strict-mode errors, and environment-specific names.
Examples
Uses a `ninjaName` property shared across modules and contrasts browser and Node.js global-object names.
What you can do after
Operate the global namespace by attaching a property through `globalThis` for access across modules.
How it connects
Connects global scope with modules, strict mode, `globalThis`, `window`, and Node.js `global`.

Also explained in

Compare how 3 books explain global object →

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.