If you have worked with JavaScript in different environments such as in browsers, Node.js, or web workers, you might have the headache of accessing the global object.
This is because in different environments the global object is different.
For example, in browsers, the global object is the window
object, but in Node.js the global object is the global
object, and in web workers it the self
object.
This is a pure headache since we had to check for all the possible variations in different environments to access the global object.
But no more headaches. 🤯
The ES2020 globalThis
keyword has come to the rescue. 🚀
Now you can use the globalThis
keyword in javascript and it automatically points us to the environment's global object.
// Get the global object in
// different JavaScript environments 🦄
console.log(globalThis);
So in browsers accessing the globalThis
will point to the window
object, in Node.js it will point to global
object and in web workers, it will point to the self
object.
- Run the above code in Node.js using repl.it to see the global object in Node.js.
- And also run the above code in Browser using JSBin to see the global object in the browser.