ES2020 - Access global scope with globalThis across different environments

ยท 2 min read
ES2020 - Access global scope with globalThis across different environments

Updated: 28/4/2020

Writing cross-platform JavaScript that can run across different environments such as NodeJS or the browser has definitely some difficulties. One of these is that we should access the global object by using a different approach based on the environment our code runs.

In browser, the window is the global object, in NodeJS it is global while for web workers it is self. Last but not least, only this is available in a shell like V8's d8 or JavaScriptCore's jsc ๐Ÿ˜ฌ

This forced us to run some custom logic to spot the global scope:

const theGlobalScopeObject =
  (typeof global !== "undefined") ? global :
    (typeof window !== "undefined") ? window :
      (typeof self !== "undefined") ? self :
        (new Function("return this"))();

With ES2020 this issue will come to an end because now we can access the global object in a unified way by calling directly globalThis. That way, we won't have to worry about the environment our application is running on.

Because of globalThis the snippet above can be changed to the following if we want to stay safe:

const theGlobalScopeObject =
  (typeof globalThis !== "undefined") ? globalThis :
    (typeof global !== "undefined") ? global :
      (typeof window !== "undefined") ? window :
        (typeof self !== "undefined") ? self :
          (new Function("return this"))();

As expected, in the browser globalThis will return the window object:

globalThis example

While in NodeJS it will return the global object:

globalThis example

Cheers!!

At the moment of this writing, globalThis is in stage 4 of the process which is considered finished

You can check browsers support here

If you want to access it safely, you can use a polyfill

TypeScript 3.4 introduced support for globalThis

NodeJS supports it from version 12+ and on

We can use it with the help of core-js

Did you like this one?

I hope you really did...

Marios_thumb

Newsletter

Get notified about latest posts and updates once a week!!