0
0
JavascriptConceptBeginner · 3 min read

What is globalThis in JavaScript: Explained with Examples

globalThis is a standard way in JavaScript to access the global object regardless of the environment (browser, Node.js, etc.). It provides a consistent reference to the global scope, replacing older environment-specific global objects like window or global.
⚙️

How It Works

Imagine you have a big room where everyone can put their stuff on a shared table. This table is the "global" space where anything placed is accessible to everyone in the room. In JavaScript, the "global object" is like that shared table.

Different environments (like browsers or Node.js) have different names for this table: browsers use window, Node.js uses global. This made it tricky to write code that works everywhere.

globalThis is like a universal name for that shared table. No matter where your code runs, globalThis always points to the global object, making your code simpler and more reliable.

💻

Example

This example shows how globalThis lets you access a global variable in any environment.

javascript
globalThis.myGlobalVar = 'Hello, world!';
console.log(globalThis.myGlobalVar);
Output
Hello, world!
🎯

When to Use

Use globalThis when you want to access or set global variables in a way that works everywhere, whether your code runs in a browser, Node.js, or other JavaScript environments.

For example, if you write a library or tool that runs in different places, globalThis helps you avoid errors caused by environment differences.

It is also useful when you want to add properties or functions globally without worrying about the environment.

Key Points

  • globalThis is the universal global object reference in JavaScript.
  • It works the same in browsers, Node.js, and other environments.
  • It replaces older, environment-specific global objects like window and global.
  • Use it to write environment-independent global code.

Key Takeaways

globalThis provides a consistent way to access the global object across all JavaScript environments.
It helps avoid bugs caused by different global object names like window or global.
Use globalThis when writing code that should run anywhere, such as libraries or shared scripts.
It allows you to safely add or read global variables without environment checks.