What is globalThis in JavaScript?

The globalThis property allows access to the global object in JavaScript, regardless of the execution environment. In JavaScript, the global object is represented by different names depending on the environment, such as window in a web browser, self in a web worker, or global in Node.js. The globalThis property provides a consistent way to access the global object across all JavaScript environments and web servers.

Example 1

If we use different keywords to access global objects, we have to write the following piece of code to get the desired output.

let findGlobal = () => {
  if (typeof self !== 'undefined') {
      return self
  };
  if (typeof window !== 'undefined') {
      return window
  };
  if (typeof global !== 'undefined') {
      return global;
   }
};
  
// Function call
console.log(findGlobal());

In the code above, we have to make a separate function which supports all types of keywords that access global objects. However, this issue can be resolved by using console.log(globalThis) to get the same output we get from the above function.

Example 2

// Function call
console.log(globalThis);
Press "Run" to see the execution.

Similarly, let's experiment with the globalThis property to get the process information by using the process object which is a global object.

Example 3

// Function call
console.log(globalThis.process);

The code output gives us information about the current Node.js process.

We now have thoroughly looked into the globalThis property. We have also seen the different names (or methods) for accessing global objects and how globalThis provides a common ground to access a global object in various JavaScript environments.

Copyright ©2024 Educative, Inc. All rights reserved