The JavaScript Global Object and globalThis: Browsers, Node.js and Workers
What the global object is, what lives on it, why it's window in browsers, global in Node.js and self in workers, how globalThis unifies them, which declarations become global properties (var yes, let no), how modules change the picture, and why polluting globals causes bugs.
kvi5hnuCode Sprout team member7 min readOn this page
When your code uses Math, parseInt, setTimeout or console without importing anything, where do those names come from? They're properties of a special object, the global object, which the JavaScript host creates before any of your code runs. Every unqualified name that isn't a local variable is eventually looked up there.
What lives on the global object
The global object starts out with:
- Language built-ins defined by ECMAScript: constants such as
undefined,NaNandInfinity; functions such asparseInt,parseFloat,isNaNandeval; constructors such asObject,Array,String,Date,Map,PromiseandError; and namespace objects such asMath,JSON,Reflect,IntlandAtomics. - Host APIs added by the environment: in browsers
document,fetch,localStorage,setTimeout,alertand hundreds more; in Node.jsprocess,Buffer,setImmediate, plus many web-compatible APIs such asfetch,URL,TextEncoderandstructuredClone.
console.log(globalThis.Math === Math);
console.log(globalThis.parseInt("42px"));
console.log(typeof globalThis.setTimeout, typeof globalThis.JSON);
console.log(globalThis.globalThis === globalThis); // it refers to itself
true
42
function object
true
The built-in names aren't reserved words, so you can shadow them with a local variable named Map or name. Treat them as if they were reserved.
One object, many names: globalThis
Different environments historically gave the global object different names:
| Environment | Traditional name | Also works |
|---|---|---|
| Browser main thread | window (also self, frames) | globalThis |
| Web workers, service workers | self | globalThis |
| Node.js | global | globalThis |
| Deno, Bun | globalThis |
Code that had to run everywhere (libraries, polyfills) used to need clumsy detection logic. globalThis (ES2020) is the standard name that works in every environment. Use it whenever you need the global object explicitly:
const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
const isNode = typeof process !== "undefined" && process.versions?.node !== undefined;
console.log({ isBrowser, isNode });
console.log(typeof globalThis.fetch); // available in browsers and modern Node.js
{ isBrowser: false, isNode: true }
function
typeof name !== "undefined" is the safe test because typeof never throws for undeclared names. Prefer testing for the feature you need (typeof globalThis.fetch === "function") over testing which environment you're in.
Which declarations become global properties?
This is where it gets subtle. In a classic browser script (a <script> without type="module"), top-level declarations create globals, but in two different ways:

// in a classic <script> in a browser
var visits = 0; // becomes window.visits
function start() {} // becomes window.start
let user = "Ana"; // a global variable, but NOT window.user
const LIMIT = 10; // same: global, but not a property
class Cart {} // same
console.log(window.visits); // 0
console.log(window.user); // undefined
console.log(user); // "Ana": still reachable from any script on the page
varand function declarations at the top level become properties of the global object.let,constandclassat the top level are global variables visible to every script on the page, stored in a separate record. They don't appear onwindow.
Modules are different. In an ES module (<script type="module">, .mjs files, or any file loaded with import) and in Node.js CommonJS files, the top level is a module scope: nothing you declare there, not even var, becomes global. That's one of the biggest benefits of modules. If you really need a global from a module, assign it explicitly: globalThis.appVersion = "2.1".
// app.js, run with: node app.js (a CommonJS file)
var counter = 1;
function helper() {}
console.log("counter" in globalThis, "helper" in globalThis); // false false
globalThis.shared = "deliberate"; // explicit globals still work
console.log(shared); // "deliberate"
(Code pasted into the Node.js REPL or run with node -e is evaluated as a classic script instead, so there var counter does become a global property.)
Accidental globals
In sloppy mode, assigning to a name that was never declared silently creates a global property. A single typo becomes a global variable:
function updateScore() {
scroe = 10; // typo: creates globalThis.scroe in sloppy mode
}
updateScore();
console.log(globalThis.scroe);
(function strictVersion() {
"use strict";
try {
totl = 5; // strict mode refuses
} catch (err) {
console.log(err.name);
}
})();
delete globalThis.scroe;
10
ReferenceError
Strict mode turns this mistake into a ReferenceError, and modules and classes are always strict. This is one of the most important reasons to write modules (part 10).
What is this at the top level?
| Context | Top-level this |
|---|---|
| Classic browser script | the global object (window) |
| ES module (browser or Node.js) | undefined |
| Node.js CommonJS file | module.exports (an empty object at first) |
Because this varies, never use it to reach the global object. That's exactly the problem globalThis solves.
Why global variables cause trouble
Every script on a page shares one global object, and that makes globals a shared, mutable namespace:
- Name collisions. Two scripts both defining a global
configorinitoverwrite each other, and third-party scripts (analytics, ads, widgets) live in the same namespace. - Clashes with built-in globals. Browsers define many globals with ordinary names. The classic trap is
name:window.nameis a special property that always converts to a string, so a top-levelvar name = 42in a classic script gives you the string"42".status,top,parent,length,history,eventandoriginare other common clashes. - Elements with an
idbecome globals. For historical reasons,<div id="cart">makeswindow.cartrefer to that element (unless a real variable namedcartexists), which can hide typos. - Hidden dependencies. A function that reads a global has an input that doesn't appear in its parameters, which makes it harder to test and reason about.
- Memory. Globals live as long as the page, so data stored in them is never garbage-collected.
The modern answer is simple: use modules. Each module has its own scope, imports and exports make dependencies explicit, and strict mode is automatic. Globals are left for genuinely global things, set up deliberately with globalThis.
Common questions
Is undefined a global property? Can it be changed?
Yes, globalThis.undefined exists, and since ES5 it's read-only and non-configurable, as are NaN and Infinity. Assigning to them is ignored in sloppy mode and throws in strict mode. But undefined isn't a reserved word, so a local variable can still shadow it; never do that.
Does window exist in Node.js?
No. typeof window is "undefined" in Node.js, Deno 2 and workers. Code that references window directly crashes there, which is why server-side rendering frameworks warn about it. Use globalThis, or check typeof window !== "undefined" first.
What's the difference between window and globalThis in a browser?
In the main thread of a page they refer to the same thing in practice. (Technically globalThis returns the WindowProxy that forwards to the current Window, the same object window returns.) In workers, window doesn't exist but globalThis and self do.
How do I list all global variables?
Object.getOwnPropertyNames(globalThis) lists the properties of the global object, built-ins included. In a browser's DevTools, comparing against a fresh blank page's list reveals what scripts added. Top-level let/const aren't properties, so they won't appear.
Summary
- The global object holds the language built-ins and the host's APIs; unqualified names are looked up there last.
- It's
windowin browsers,selfin workers andglobalin Node.js;globalThis(ES2020) works everywhere. - In classic scripts, top-level
varand function declarations become global object properties, whilelet,constandclassare global variables without becoming properties. - Modules (and Node.js CommonJS files) have module scope: nothing becomes global unless you assign to
globalThis. - Sloppy mode turns assignments to undeclared names into accidental globals; strict mode throws instead.
- Avoid globals: they collide (watch out for
nameand element IDs), hide dependencies and never get freed. Use modules.
Practice Questions
In a classic browser script, which of these create a property on window: var a, let b, function c() {}, const d, e = 1 (sloppy mode)?
Answer
a, c and e. let and const create global variables that aren't properties of the global object.
Why does this code print "string" in a classic browser script?
var name = 7;
console.log(typeof name);
Answer
Top-level var becomes a property of window, and window.name is a special built-in property that converts every value assigned to it into a string. Use modules or a different name.
What does typeof globalThis return?
Answer
"object". The global object is an ordinary object (in browsers, technically a WindowProxy).
You need a value to be available everywhere in an app built from ES modules. What are your options?
Answer
The recommended way is to export it from a module and import it where needed. If it truly must be global (for example, for a polyfill), assign globalThis.name = value explicitly, ideally once, at startup.
Why does "use strict" help with global variables?
Answer
In strict mode, assigning to an undeclared variable throws a ReferenceError instead of silently creating a global property, so typos are caught immediately.
Previous: JavaScript Symbols: Unique Keys, the Global Registry and Well-Known Symbols
Next: Primitives vs References in JavaScript: Copying, Comparing and Mutating Values

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.