Skip to main content

Command Palette

Search for a command to run...

A simple guide to Global Obejct and Globalthis

Updated
2 min readView as Markdown
A simple guide to Global Obejct and Globalthis

What is Global Object ?

Global objects are the special types of objects in JavaScript,these are present on the top most scope of the environment, it serves as global container to acess all the globally available variables,functions and objects.

Global objects in different environment

Browser

In Web Browsers window object is the Global object from where we access the functions like setTimeout(), or objects like document and navigator are the property of window object, which mean we access them throungh window.

Node.js

In Node.js environment global is the global object, that provides the access of variables,objects and functions throughout the application without any import statement,It works similar like window in Web Browsers.

Web Workers

In a Web Worker the global object is accessed by the self keyword,This object belongs to the WorkerGlobalSpace interface and is distinct from the browser's window object.

Problems of Global objects

--Different environment have different global object

--Debugging Challenges

--Naming Conflict

--Hard to maintain

--Different syntax for different environment

What is Global this ?

globalthis is the standraized way to access global object in all environment(Browser,Node.js,Web Workers)

Declaration of globalthis

function setTimeout() {
  return typeof globalThis.setTimeout === "function";
}

console.log(setTimeout());
// Expected output (in a browser): true

Advantages of globalthis

--It provides consistency

--Works on all Environment

--Clean Code

--Debugging goes easier