What is the difference between window, document, and globalThis?
Three related but distinct globals in the browser.
window — the browser's global object: the tab/window, with APIs like setTimeout and location.
document — the page itself (the DOM tree); a property of window.
globalThis — a standard reference to the global object in any environment (browser, Node, worker).
Use globalThis for portable code that must run beyond the browser.
// Browser
console.log(window === globalThis); // true (in browsers)
console.log(window.document); // The DOM
console.log(window.location); // URL info
console.log(window.navigator); // Browser info
// document — DOM manipulation
document.querySelector('#app');
document.createElement('div');
document.title = 'My Page';
// globalThis — universal
console.log(globalThis); // window (browser) or global (Node)
globalThis.myVar = 42; // Available globally
// Cross-environment code
const isNodeJS = typeof globalThis.process !== 'undefined';
const isBrowser = typeof globalThis.window !== 'undefined';window = browser global (all globals, browser APIs). document = DOM tree (HTML manipulation). globalThis = universal global (works everywhere). In browsers: window === globalThis.
In Node.js: global === globalThis. Use globalThis for environment-agnostic code.
window = browser global, document = DOM, globalThis = universal (ES2020). Know that window is browser-only (not in Node.js or Workers). globalThis for cross-environment code.
In browsers: window === globalThis === self.