JavaScript Reference ยท Global Functions and Values
The globalThis property
Reference for globalThis: one name for the global object in browsers, workers and Node.js, how it relates to window, self and global, and var versus let.
globalThis is a property that always holds the global object, whatever environment your code runs in. In a browser page it is window, in a worker it is self, and in Node.js it is the global object. Before it existed, portable code had to probe for each name in turn.
The global object holds the built-in functions and values such as parseInt, Math and undefined, plus platform features like setTimeout or document.
globalThis.Math === Math; // true
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
globalThis
globalThis.propertyName
Value: the global object of the current realm (an object, not a copy).
Property attributes: writable and configurable, not enumerable, so it does not show up in for...in on the global object.
Usage notes
- One name everywhere. Use
globalThisin libraries that run in browsers, workers and Node.js. In a browser,window === globalThison the main thread. varand function declarations at the top level of a classic script become properties of the global object.let,constandclassdeclarations create global bindings that are not properties. Inside ES modules, top-level declarations stay local to the module.- Feature detection:
"fetch" in globalThisis a safe test that never throws aReferenceError, unlike a barefetchreference to a missing name. - Avoid adding globals. Assigning to
globalThiscreates shared mutable state that every script can overwrite. Prefer modules. - Inside strict mode and modules,
thisat the top level of a module isundefined, so do not use it to reach the global object. - Frames and iframes each have their own global object and their own
globalThis. - Other environments may add or lack properties:
documentexists only on browser main threads, andprocessonly in Node.js-like runtimes.
Browser support
globalThis is supported in all current browsers and runtimes. Only very old browsers need the fallback chain of self, window, global.
Related
undefined,NaN,Infinity- Lessons: Scope, Browser object model