Skip to main content

Command Palette

Search for a command to run...

global and globalThis

Updated
2 min read

Global : -

The interface of global object is depends upon the platform or execution context in which the script is executing.

Such as for : -

  • Node.js -> global

  • Window -> window

  • WorkerSpace -> self

since each environment have to deal with different aspect. such as

  • Browser: DOM, UI, storage, timers, etc.

  • Web Worker: timers, fetch, messaging, etc. (no DOM access)

  • Node.js: filesystem, process information, networking, buffers, etc.

Developers often had to detect the runtime:

if(typeof window !=='undefine'){
    console.log("window");
}else{
    console.log("global");
}

globalThis :-

Traditionally, It is hard to find the global object due to different runtime environment.

Here globalThis provide the easier the program.

globalThis is a property which allow one to access the global object, regardless of runtime environment.

In Node.js

console.log(globalThis === global);
console.log(globalThis);

returns

true
global

In window

console.log(globalThis === window);
console.log(globalThis);

returns

true
window

In webWorker

console.log(globalThis === self);
console.log(globalThis);
true
self

globalThis guarantee to access the global object regardless of the environment. It make sure the easy work with global object in window and non window environment.

Property of globalThis

{
    enumerable : false,
    writable : true,
    configurable : true
}