What is ‘globalThis’ in JavaScript?

·

2 min read

What is ‘globalThis’ in JavaScript?

The ecosystems where JavaScript runs have increased widely. Starting with the browsers, it has now extended to servers, smartwatches, and even in the field of AI or ML.

To access the global object in each environment, JavaScript has its own object model and provides a different syntax.

For example, in the browser, you can access the global object using these keywords window, self or frames.

console.log(window);    

// Window {...}

Then, in the Node.js environment, these keywords — window, self or frames — will not work. Accessing them in the Node.js environment will throw an error — ReferenceError: window is not defined. So, for accessing the global object, we need globlal.

console.log(global);    

// Object [global] {...}

Coming to the Web Workers, the only global object which is accessible is self, which returns the DedicatedWorkerGlobalScope.

console.log(self);    

// DedicatedWorkerGlobalScope {...}

These different ways of referencing the global object in different environments have made it tough to write portable JavaScript code that works in multiple or all environments.

The way to solve this is by using the standard property name globalThis which is available in all the environments.

// In browser
console.log(globalThis); // window

// In node.js
console.log(globalThis); // Object[global]{...}

// Web Worker
console.log(globalThis); // DedicatedWorkerGlobalScope {...}

Mathias Bynens has created a polyfill that works seamlessly for every environment which looks like this:

const getGlobalThis = () => {
  if (typeof globalThis !== 'undefined') return globalThis;
  if (typeof self !== 'undefined') return self;
  if (typeof window !== 'undefined') return window;
  if (typeof global !== 'undefined') return global;
  if (typeof this !== 'undefined') return this;
  throw new Error('Unable to locate globalThis');
};

var globalThis = getGlobalThis();

Browser compatibility of globalThis