globalThis in JavaScript

Managing global variables and objects across different environments (like browsers and Node.js) can be tricky in JavaScript.

Each environment has its way of accessing the global object. Browsers use window, while Node.js uses global.

This can lead to confusion and bugs, especially when writing code intended to run in multiple environments.

To address this issue, JavaScript introduced globalThis in ECMAScript 2020. globalThis provides a standard way to access the global object, regardless of the environment.

Let's delve into what globalThis is and how to use it.

Why use it?

Before globalThis, developers had to write conditional code to handle different environments:

let globalStuff = typeof window !== 'undefined' ? window :
                typeof global !== 'undefined' ? global :
                typeof self !== 'undefined' ? self : this;

globalThis simplifies this by providing a consistent and reliable way to access the global object.

How to

Using globalThis is straightforward. Here are some common use cases:

Accessing Global Variables: You can read or write global variables directly using globalThis.

globalThis.myGlobalVar = "Hello, World!";
console.log(globalThis.myGlobalVar); // Outputs: Hello, World!

Defining Functions: You can define functions on the global object.

globalThis.myGlobalFunction = function() {
    return "This is a global function.";
};
    
console.log(globalThis.myGlobalFunction()); // Outputs: This is a global function.

Cross-Environment Compatibility: Code written with globalThis works seamlessly across different JavaScript environments.

if (globalThis.setTimeout) {
    console.log("setTimeout is available");
}
JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.