Skip to main content

Command Palette

Search for a command to run...

global and globalThis Explained!!

Updated
2 min read
global and globalThis Explained!!
B
I am into development and powerlifting.

lets see what is global first:

Global object is top level scope container i.e, it holds built-in variables, functions and modules which are available everywhere in the app without needing to require or import anything.

global object can be different in different environments:

  1. Browser: The global object is window object.

  2. Node: The global object is global.

  3. Workers: The global object is self

Lets take some examples in node js environment:

//functions and utilities
console.log("hello")     // global.console
setTimeout(() => {}, 0)  // global.setTimeout
setInterval(() => {}, 0) // global.setInterval

//process & environment 
process.env  //global.process.env
process.argv //global.process.argv

globalThis

globalThis is simple and standardized way to refer to global obj across all JavaScript environments.

The problem globalThis solves:

// Browser
Global object is window

// Node
Global object is gloabl

// Web Workers
Global object is self

Before globalThis, if writing code that runs on multiple environments, we had to use some checks to declare the global object

const globalObj = typeof window !== 'undefined' ? window
                : typeof global !== 'undefined' ? global
                : typeof self !== 'undefined' ? self
                : undefined;

globalThis eliminates this issue and it becomes the window/global/self object.

// All of these are the same thing in Node.js:
global === globalThis          // true
global.process === globalThis.process  // true 

here globalThis is just an alias for global.

Hope this blog helps you in understanding global and globalThis.