In JavaScript, this execution context has a special object called the global object. The global object is the root of the entire program.
The global object varies depending on the environment in which it runs.
- In browsers, the global object is
window. - In server environments like Node.js, the global object is
global.
The global object is the main container for all variables, functions, and objects defined in a program.
Furthermore, it acts as a common access point to functions and objects predefined by the environment, such as console, setTimeout, and others.
Later, the reserved word globalThis was introduced to provide a uniform way to refer to the global object, regardless of the environment.
In the Browser window
In web browsers, the global object is window. It is a special object that:
- Represents the browser window or tab where the script is running.
- Contains methods, properties, and objects related to the browser and the document (e.g.,
alert,document, etc.).
Let’s see an example:
console.log(window); // Displays the complete window object
console.log(window.alert); // alert function
console.log(window.document); // The DOM of the current document
We can also add our own variables to the window object, which will make them accessible anywhere in the program.
window.myGlobalVariable = "Hello, world"; // Not recommended!
console.log(window.myGlobalVariable); // "Hello, world"
In general, this is almost always a bad practice.
In Environments like Node.js global
In runtimes like Node.js, we access the global object with the reserved word global.
console.log(global); // Displays the global object in Node.js
We can define global properties on this object, but again, it is not a recommended practice.
global.myProperty = "Global value";
console.log(global.myProperty); // "Global value"
The Standard Solution globalThis
In modern environments, ECMAScript introduces globalThis as a unified way to access the global object.
This is independent of whether we are in a browser, Node.js, or any other environment. That is,
- In browsers,
globalThisis equivalent towindow. - In Node.js,
globalThisis equivalent toglobal.
globalThis.myGlobal = "Available in all environments";
console.log(globalThis.myGlobal); // "Available in all environments"
This allows us to write portable code (that works in both browsers and servers) without worrying about the context.
Although it is tempting to use the global object to store data, it is not a safe or advisable practice (in fact, it’s quite messy).
However, it can be useful at times, or sometimes we have no other choice. Always try to avoid it, but sometimes it can get you out of a bind.
