Chapter 06 โ Scope (Global, Function, Block)
๐ Definition
Scope defines the region of a program where a variable is accessible.
๐ Explanation
JavaScript uses lexical (static) scoping โ scope is determined by where code is written, not where it is called.
| Scope | Created by | Holds |
|---|---|---|
| Global | Top of the script | var / let / const at the top level |
| Function | Any function body | var, let, const, parameters |
| Block | {} of if, for, while, etc. |
Only let and const |
| Module | An ES module file | Top-level declarations are module-scoped (not global) |
๐ป Code Example โ Function vs Block Scope
function test() {
if (true) {
var a = 1; // function-scoped
let b = 2; // block-scoped
const c = 3; // block-scoped
}
console.log(a); // 1 โ
console.log(b); // โ ReferenceError
console.log(c); // โ ReferenceError
}๐ป Code Example โ Lexical (Static) Scoping
let x = "global";
function outer() {
let x = "outer";
function inner() {
console.log(x); // "outer" โ lexical lookup
}
inner();
}
outer();Even if inner() is called from somewhere else, it still resolves x to "outer", because that's where it was defined.
๐ป Code Example โ Scope Chain
const a = 1;
function f1() {
const b = 2;
function f2() {
const c = 3;
console.log(a, b, c); // 1 2 3 โ walks up the chain
}
f2();
}
f1();๐ป Code Example โ Module Scope
// math.js
export const PI = 3.14; // module-scoped, NOT global
const internal = "private"; // not exported โ invisible outside
// app.js
import { PI } from "./math.js";
console.log(PI); // 3.14
console.log(internal); // โ ReferenceError๐ป Code Example โ Block Scope Saves Loops
// var leaks out
for (var i = 0; i < 3; i++) {}
console.log(i); // 3 โ leaked
// let stays inside
for (let j = 0; j < 3; j++) {}
console.log(j); // โ ReferenceError๐ Real-World Impact
- Prefer
consteverywhere; useletonly when reassignment is needed; avoidvar. - Modules give natural encapsulation โ your "private" helpers stay private if you don't export them.
๐ฏ Likely Interview Questions
- What's the difference between function and block scope?
- What is lexical scoping?
- Why is
varconsidered dangerous? โ Function-scoped (not block-scoped), hoisted toundefined, can leak out of loops/blocks. - Scope chain explained.
- Output prediction:
function outer() { const greeting = "hi"; return function () { console.log(greeting); }; } const fn = outer(); fn(); // "hi" โ closure preserves outer scope