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

JS globalThis

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

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.

Example: 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.

Example: 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.

Example: Portable Global Access

javascript
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

javascript
// Prefer modules/imports over touching globalThis directly
import { helper } from './utils.js';
console.log(helper());

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.