Lesson 50: Mastering JavaScript Global Object with challenges!

manoj ymkmanoj ymk
5 min read

✅ 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.

EnvironmentName
Browserwindow
Node.jsglobal
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

  1. let, const, and class NEVER attach to the global object — only var and function declarations do (outside modules).

  2. Modules (<script type="module">) create their own scope, so even var doesn’t attach to window.

// 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 ❌
  1. Global properties declared in strict mode behave differently:
"use strict";
undeclared = 123; // ❌ ReferenceError (does NOT create global)
  1. 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)
  1. 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

FeatureBrowser (window)Node.js (global)Worker (self)
DOM access
setTimeout
document
globalThis

🔹 3. Challenge Me Deeply

🟢 Basic

  1. What’s the difference between let, var, and const regarding global scope?

  2. How can you safely attach a value to the global object across all environments?

🟡 Intermediate

  1. Why doesn’t let x = 5; attach x to window?

  2. Create a polyfill for Array.prototype.flat() if it’s not supported.

  3. Inside a <script type="module">, try to access var x = 5; via window.x — what happens?

🔴 Advanced

  1. Create a utility function isGlobalRef(x) that returns true if x refers to a global variable.

  2. In strict mode, assign to an undeclared variable — explain what happens and why.

  3. Override the global alert() function temporarily and then restore it.

  4. Explain how using too many globals can lead to memory leaks in SPAs.

  5. In Node.js, modify the global object and observe its visibility across modules.

🎯 Brain-Twister

  1. 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

ToolUsage of Global
BabelChecks globalThis for polyfills
WebpackUses 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 TypeAdds 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:

  1. Create a window.AppConfig object with some default keys.

  2. Create a floating UI panel using HTML/CSS.

  3. On load, read and display all keys from AppConfig.

  4. Use Object.keys(globalThis.AppConfig) to display them dynamically.

  5. 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.

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk