Codementor Events

To clean it up - globalThis is here!

Published Jul 20, 2019
To clean it up - globalThis is here!

We all like to keep everything clean and tidy. There is no surprise in this.

See, the only thing is that in JavaScript we have to keep our code clean and eloquent as well as our houses or apartments.

We, as people, don't like confusion and making unnecessary things that can decrease our confidence.

Not so long time ago, an enhanced window object arrived in the web browsers to stop the confusion and writing unnecessary code.

1. What am I exactly trying to tell you?

I'm talking about globalThis, which provides us with a unified mechanism to access the global window object in multiple environments.

No matter if you work with Node.js or with JavaScript on the client-side.

As you may already know, to access global window object in Node.js, you had to call global, to access it on client-side JavaScript, you had to use window object. Can you see the inconsistency?

Below you can see a standard check of the global window object before globalThis arrived.

if (typeof window !== 'undefined') {
   return window;
}

if (typeof global !== 'undefined') {
   return global;
}

With the arrival of a new window object, you can write:

const theGlobalThis = globalThis;

If you try to type globalThis in the console, you will get a window object.

1.1 Does it mean that I can't use "window" object anymore?
Don't worry about that; you can still use it as you were before, globalThis is an addition to keep all environments consist, where JavaScript is.

2. What is the web browser support?

The vital thing you have to know is that it is a proposal in stage 3. It's close to being an announced standard.

However, you can start using it as it was implemented in the major web browsers, even if it is not a standard. Below you can see the list of web browsers supporting globalThis:

  1. Chrome, 71+
  2. Firefox, 65+
  3. Safari, 12.1+

Supported environments:

  1. Node.js, 12+

There is also support from Babel

3. Summary

This post has a purely informative purpose if you'd like to find out more details about globalThis, please visit V8 Blog post.

This article was originally written on: Robert Wozniak - Dev Blog

Discover and read more posts from Robert Wozniak
get started