Lesson 50: Mastering JavaScript Global Object with challenges!
✅ What is the Global Object?
The global object is a built-in object that provides access to global variables and functions — values that are available anywhere in your code.
| Environment | Name |
| Browser | window |
| Node.js | global |
| All (standard) | globalThis |
✅ Example
// In browser:
console.log(window.alert === alert); // true
// Modern cross-env way:
console.log(globalThis.setTimeout === setTimeout); // true
✅ Declaring Globals
var foo = 42;
console.log(window.foo); // 42 ✅ becomes global property
let bar = 100;
console.log(window.bar); // undefined ❌ not global
✅ Adding Custom Globals
window.appConfig = {
apiKey: "abc123"
};
console.log(appConfig.apiKey); // "abc123"
🔹 2. Fill Any Gaps
✅ Hidden Behaviors & Edge Cases
let,const, andclassNEVER attach to the global object — onlyvarand function declarations do (outside modules).Modules (
<script type="module">) create their own scope, so evenvardoesn’t attach towindow.
// script.js
var test = "hi";
console.log(window.test); // "hi"
// script.module.js
// <script type="module" src="script.module.js">
var test = "hi";
console.log(window.test); // undefined ❌
- Global properties declared in
strict modebehave differently:
"use strict";
undeclared = 123; // ❌ ReferenceError (does NOT create global)
- Function declarations inside blocks are not truly global (non-standard behavior in old browsers):
if (true) {
function foo() {}
}
console.log(window.foo); // ❌ undefined (in strict mode)
- Not all built-ins are own properties of the global object:
console.log(globalThis.hasOwnProperty('Math')); // false
console.log('Math' in globalThis); // true ✅
✅ Browser vs Node.js vs Workers
| Feature | Browser (window) | Node.js (global) | Worker (self) |
| DOM access | ✅ | ❌ | ❌ |
setTimeout | ✅ | ✅ | ✅ |
document | ✅ | ❌ | ❌ |
globalThis | ✅ | ✅ | ✅ |
🔹 3. Challenge Me Deeply
🟢 Basic
What’s the difference between
let,var, andconstregarding global scope?How can you safely attach a value to the global object across all environments?
🟡 Intermediate
Why doesn’t
let x = 5;attachxtowindow?Create a polyfill for
Array.prototype.flat()if it’s not supported.Inside a
<script type="module">, try to accessvar x = 5;viawindow.x— what happens?
🔴 Advanced
Create a utility function
isGlobalRef(x)that returns true ifxrefers to a global variable.In strict mode, assign to an undeclared variable — explain what happens and why.
Override the global
alert()function temporarily and then restore it.Explain how using too many globals can lead to memory leaks in SPAs.
In Node.js, modify the global object and observe its visibility across modules.
🎯 Brain-Twister
- What’s wrong here?
(function () {
var test = "hello";
window.test = test;
})();
console.log(test); // ??
🔹 4. Interview-Ready Questions
✅ Conceptual
What is the global object, and how does it differ between environments?
Why is
globalThisintroduced and what problem does it solve?
✅ Scenario-Based
- You want to add a global
configobject that works both in the browser and Node.js. How do you do it safely?
✅ Debugging-Style
- A dev writes:
let userName = "Alice"; console.log(window.userName); // undefined— why doesn’t it work?
✅ Best Practices
✅ DO:
Use
globalThisfor cross-platform support.Limit globals — wrap values in namespaces if needed.
❌ AVOID:
Overwriting native global properties (like
Array,Promise).Using undeclared variables — might pollute global scope in sloppy mode.
🔹 5. Real-World Usage
✅ Use Cases
Polyfills: Patch missing features
Global Config: Store app-wide config (e.g.
window.appSettings)Global Event Buses: Basic pub/sub communication
✅ Libraries & Frameworks
| Tool | Usage of Global |
| Babel | Checks globalThis for polyfills |
| Webpack | Uses globalThis to inject runtime |
| React (DevTools) | Hooks onto window.__REACT_DEVTOOLS_GLOBAL_HOOK__ |
🔹 6. Remember Like a Pro
✅ Mnemonics
- WIG: Window (Browser), Global (Node),
globalThis(Universal)
✅ Visual Summary
┌──────────────────────────┐
│ Global Object │
├────────┬─────────────────┤
│Browser │ window │
│Node.js│ global │
│All │ globalThis │
└────────┴─────────────────┘
| Declaration Type | Adds to Global Object? |
var | ✅ Yes |
let / const | ❌ No |
function | ✅ Yes (non-module) |
class | ❌ No |
🔹 7. Apply It in a Fun Way
🔧 Mini Project: “GlobalConfig Viewer”
Let’s build a tiny debug widget that shows all global config values.
📦 Steps:
Create a
window.AppConfigobject with some default keys.Create a floating UI panel using HTML/CSS.
On load, read and display all keys from
AppConfig.Use
Object.keys(globalThis.AppConfig)to display them dynamically.Add a button to
JSON.stringifythe config for copy-paste.
➕ Extensions:
Add ability to edit the config values live.
Export config as a
.jsonfile.
🧠 (Optional - Extra Value)
✅ Open Source Projects Using This
Core-js – polyfills many global features.
Lodash – attaches to
globalif in Node.[React DevTools] – hooks into the browser via
window.
✅ Common Mistakes
Assuming
letvariables are global.Using
windowin Node.js or workers.Polluting global scope with too many unrelated properties.
✅ Performance Tips
Avoid attaching large objects to the global object — leads to memory retention.
Use modules to encapsulate functionality instead of global properties.