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
, andclass
NEVER attach to the global object — onlyvar
and function declarations do (outside modules).Modules (
<script type="module">
) create their own scope, so evenvar
doesn’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 mode
behave 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
, andconst
regarding global scope?How can you safely attach a value to the global object across all environments?
🟡 Intermediate
Why doesn’t
let x = 5;
attachx
towindow
?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 ifx
refers 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
globalThis
introduced and what problem does it solve?
✅ Scenario-Based
- You want to add a global
config
object 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
globalThis
for 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.AppConfig
object 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.stringify
the config for copy-paste.
➕ Extensions:
Add ability to edit the config values live.
Export config as a
.json
file.
🧠 (Optional - Extra Value)
✅ Open Source Projects Using This
Core-js – polyfills many global features.
Lodash – attaches to
global
if in Node.[React DevTools] – hooks into the browser via
window
.
✅ Common Mistakes
Assuming
let
variables are global.Using
window
in 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.
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
