DEV Community

Scott Beeker
Scott Beeker

Posted on

Javascript Dictionary: globalThis

Image description

globalThis

Is a built-in object introduced in ECMAScript 2020 that provides a standard way to access the global object across different environments , such as browser and Node.js. This object allows developers to write code that is more portable and works consistently across different environments.

Previously, different JavaScript environments had different ways to access the global object, such as window in browsers and global in Node.js. The globalThis object serves as a universal way to access the global object , making it easier to write code that can run in different environments without having to modify it.

Polyfills are available for older environments that do not support globalThis, and TypeScript 3.4 introduced support for type-checking globalThis.

Overall, globalThis is an important addition to the JavaScript language that helps to improve the consistency and portability of JavaScript code across different environments.

if (typeof globalThis === 'object') {
  // globalThis is defined in the current environment
  globalThis.myVar = 'Hello world';
} else {
  // globalThis is not defined, falling back to other methods
  if (typeof window === 'object') {
    window.myVar = 'Hello world';
  } else if (typeof self === 'object') {
    self.myVar = 'Hello world';
  } else if (typeof global === 'object') {
    global.myVar = 'Hello world';
  }
}

console.log(myVar); // Outputs 'Hello world' in any environment
Enter fullscreen mode Exit fullscreen mode

This code checks if the

globalThis
Enter fullscreen mode Exit fullscreen mode

property is defined in the current environment, and if it is, sets a variable called myVar on it. If globalThis is not defined, the code falls back to other methods to set the variable on the global object. Finally, the code outputs the value of myVar to the console, which should be 'Hello world' in any environment.

Top comments (0)