Global Scope
Global Scope
Section titled “Global Scope”Introduction
Section titled “Introduction”The global scope is the top-level scope in JavaScript. Variables declared in the global scope are accessible from anywhere in the code.
Visual Explanation
Section titled “Visual Explanation”flowchart TD A["Global Scope"] B["Module 1"] C["Module 2"] D["Module 3"]
A --> B A --> C A --> D
Note["Sharing via global scope causes coupling"] style A fill:#ff9900Key Points
Section titled “Key Points”// In a browser, the global scope is 'window'var globalVar = 'I am global';console.log(window.globalVar); // 'I am global' (in browser)
// In Node.js, the global scope is 'global'// In ES modules, top-level scope is module scopeWhy Avoid Global Scope
Section titled “Why Avoid Global Scope”// ❌ Global pollutionlet count = 0;function increment() { count++; } // modifies global
// ✅ Encapsulatedfunction createCounter() { let count = 0; return () => count++;}Summary
Section titled “Summary”- Global scope is accessible everywhere
- Minimize global variable usage
- Use modules and functions for encapsulation
- Globals cause naming conflicts and hard-to-debug code