JS globalThis
In this page:
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
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
// 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
// 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
// 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
// Prefer modules/imports over touching globalThis directly
import { helper } from './utils.js';
console.log(helper());
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: