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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay