sajad torkamani

In a nutshell

globalThis is a new ES11 feature that provides a standard and cross-platform way to access the global this value. globalThis means that instead of doing something like the below to get the global object in a cross-platform manner:

const getGlobal = function () {
  if (typeof self !== 'undefined') { return self; }
  if (typeof window !== 'undefined') { return window; }
  if (typeof global !== 'undefined') { return global; }
  throw new Error('unable to locate global object');

const globals = getGlobal();

if (typeof globals.setTimeout !== 'function') {
  // no setTimeout in this environment!

You can instead do:

if (typeof globalThis.setTimeout !== 'function') {
  // no setTimeout in this environment!

globalThis should work across window, non-window environments, client-side scripts in strict or non-strict mode, web workers, or Node.js.


Tagged: JavaScript

Leave a comment

Your email address will not be published. Required fields are marked *