Question presented to candidate: "Before globalThis existed, how would you reliably access the global object in code that needed to run in BOTH a browser and Node.js, and what problem does globalThis actually solve?"
What a strong answer should cover:
- 📌 Interview term:
globalThis— a standard (ES2020), environment-independent reference to the global object, working identically whether the code runs in a browser (where it was previouslywindow/self), Node.js (previouslyglobal), or a Web Worker (previouslyself). - 📌 Interview term: the real, direct answer to the prompt's problem — before
globalThis, code that needed to run in multiple environments had to use a real, awkward feature-detection dance (checkingtypeof window !== "undefined" ? window : typeof global !== "undefined" ? global : self) just to reliably reach the global object —globalThisgenuinely eliminates that entirely with one universal name. - 📌 Interview term: it's the same underlying object, just a universal name — verified directly: setting a property via
globalThis.x = valuegenuinely makes that property visible as a plain global identifier in the SAME environment —globalThisdoesn't create a new, separate global scope; it's a real, direct reference to the one that already exists. - A precise answer names that
globalThisis genuinely useful for polyfill/feature-detection code and libraries that must run correctly in multiple JavaScript environments without knowing in advance which one they're in — the real motivating use case the standard was created for. - A precise answer names that despite
globalThisexisting, directly relying on implicit globals (assigning to an undeclared variable, reading an unexpected global) remains poor practice in application code —globalThissolves environment PORTABILITY, not the general advice to avoid polluting global state.
Clarifying questions expected:
- None — this is a definitional/technical question; naming the real cross-environment problem it solves (not just "it's the global object") is the strong signal.
Code / implementation expected: Optional — showing a property set via globalThis becoming visible as a plain identifier demonstrates it is the real, same global object, not a separate abstraction.