← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 8 of 12

JS globalThis

globalThis is one name that always points to the top-level shared space, no matter where JavaScript runs. It is like a master key that works in every building.
Syntax
javascript
globalThis.propertyName = value;
globalThis.propertyName;

What Is globalThis

globalThis is a standard property that refers to the global object no matter which JavaScript environment the code runs in, unifying what used to require different names per platform.

उदाहरण: What Is globalThis

javascript
console.log(typeof globalThis); // "object" in every environment

globalThis in Node.js

In Node.js, globalThis points to the same global object you'd otherwise access as global, giving Node code a way to reference global state without a Node-specific identifier that wouldn't work in a browser.

उदाहरण: globalThis in Node.js

javascript
// In Node.js: globalThis === global
console.log(typeof globalThis);

globalThis and Browser Code

In browsers, globalThis refers to the same object as window (or self inside a worker), so browser code can use it without assuming a specific browser global exists.

उदाहरण: globalThis and Browser Code

javascript
// In browsers: globalThis === window
console.log(globalThis === window);

Portable Global Access

Because globalThis works identically everywhere, code that needs to check for or attach to the global object — like a polyfill — can do so without environment-detection branching.

उदाहरण: Portable Global Access

javascript
// Check whether `!globalThis.myPolyfill`
// Check whether `!globalThis.myPolyfill`
if (!globalThis.myPolyfill) {
  // Assign `function () { return "polyfilled"; }` to `globalThis.myPolyfill`
  // Assign `function () { return "polyfilled"; }` to `globalThis.myPolyfill`
  globalThis.myPolyfill = function () { return "polyfilled"; };
}
// Print `globalThis.myPolyfill()` to the console
// Print `globalThis.myPolyfill()` to the console
console.log(globalThis.myPolyfill());

Best Practices with globalThis

Prefer explicit imports and modules over touching globalThis directly; reserve it for genuine cross-environment library code that must interact with the global object safely.

उदाहरण: Best Practices with globalThis

javascript
// Prefer modules/imports over touching globalThis directly
import { helper } from './utils.js';
console.log(helper());
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.