globalThis
Version: ES2020
Level: Beginner
In the past, there has been no consistent way to access the global object in JavaScript. In Node it’s referred to as global
while in browsers you’d use window
(despite that being a WindowProxy and not the actual global object, which is not directly accessible in browsers). In other places like with web workers, you don’t have either, instead relying on a self
property in the top level context. self
also exists in normal browser code, referencing the window
object, but it does not exist in Node.
The introduction of globalThis
in ES2020 changes that by acting as a standard way to access the global object in JavaScript - or at least what passes for it. What it really represents is the value of this
in the global context. As we’ve seen with browsers this isn’t exactly the global object, instead being a WindowProxy, but, you know, close enough.
// in browsers (non-module, top level)
console.log(globalThis === this); // true
console.log(globalThis === window); // true
// in Node (non-module, top level)
console.log(globalThis === this); // true
console.log(globalThis === global); // true
Having globalThis
now makes it easier to write code that is cross-compatible with multiple JavaScript environments by having a single way to access the global object… assuming they support it (it’s still fairly new as of this writing, though modern browsers and Node support it currently).
More info: