JS globalThis
In this page:
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.
Example: 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.
Example: 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.
Example: 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.
Example: Portable Global Access
if (!globalThis.myPolyfill) {
globalThis.myPolyfill = function () { return "polyfilled"; };
}
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.
Example: 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: