Scope, hoisting and execution context
Scope decides where a variable can be accessed, hoisting decides what exists before a line runs, and the execution context with the call stack explains both. Understanding them explains bugs like "no error, but undefined (or NaN)".
9.1 Problem: why is the price NaN?
- getPrice declares discount with var inside an if block.
- getPrice(1500) gives 1400, but getPrice(500) gives NaN instead of an error.
- var ignores block scope, so discount belongs to the whole function.
- Hoisting prepares discount at the top with undefined; 500 - undefined = NaN.
function getPrice(price) { if (price > 1000) { var discount = 100; } return price - discount;} console.log(getPrice(1500));console.log(getPrice(500));> 1400> NaN9.2 Scope: where a variable lives
- Global scope: shop. Function scope: user (inside checkout). Block scope: coupon (inside the if).
- Inside the block all three are visible.
- Outside the block coupon gives a ReferenceError.
const shop = "Flipkart"; function checkout() { const user = "Riya"; if (user) { const coupon = "SAVE10"; console.log(shop, user, coupon); } console.log(coupon);} checkout();> Flipkart Riya SAVE10ReferenceError: coupon is not defined9.3 Scope chain
- If a variable is not in the current scope, JavaScript looks in the parent, then its parent, up to global.
- The search always goes from inside to outside, never the other way.
- Not found even in global: ReferenceError.
- Step 1
1.Block scope: coupon
- Step 2
2.Not here? Function scope: user
- Step 3
3.Not here? Global scope: shop
- Step 4
4.Not found anywhere: ReferenceError
Search goes inside to outside only
9.4 Hoisting: var, functions, let and the TDZ
- Before the code runs, JavaScript registers all declarations in memory.
- var is hoisted with undefined: reading city before its line gives undefined, not an error.
- A function declaration is hoisted with its full code: greet() works before its definition.
- let and const are hoisted but get no value; until the declaration line they are in the TDZ (Temporal Dead Zone): ReferenceError.
console.log(city);var city = "Pune"; greet();function greet() { console.log("Hi from greet");} console.log(pin);let pin = 411001;> undefined> Hi from greetReferenceError: Cannot access 'pin' before initialization| Declaration | Hoisted? | Value before its line | Scope |
|---|---|---|---|
| var | Yes | undefined | Function |
| let | Yes | TDZ: ReferenceError | Block |
| const | Yes | TDZ: ReferenceError | Block |
| function declaration | Yes, with full code | Callable | Function |
| const arrow / expression | Like const | TDZ: ReferenceError | Block |
9.5 Execution context: 2 phases
- When code starts, and on every function call, JavaScript creates an execution context.
- Memory phase: var gets undefined, functions get their full code, let / const stay uninitialized (TDZ).
- Execution phase: the code runs line by line and values are assigned.
- Hoisting is not magic: it is simply the result of the memory phase.
- Step 1
1.Context created (program start or function call)
- Step 2
2.Memory phase: var = undefined
- Step 3
3.Memory phase: functions = full code, let / const = TDZ
- Step 4
4.Execution phase: run line by line
- Step 5
5.Values assigned as each line runs
9.6 Call stack
- When one function calls another, the call stack tells JavaScript where to come back.
- Calling placeOrder pushes its context on top; calling pay pushes pay above it.
- When pay finishes it is popped and control returns to placeOrder.
- LIFO (last in, first out), like a stack of plates.
function pay() { console.log("3. pay");} function placeOrder() { console.log("2. placeOrder"); pay(); console.log("4. back in placeOrder");} console.log("1. start");placeOrder();console.log("5. end");> 1. start> 2. placeOrder> 3. pay> 4. back in placeOrder> 5. end- Step 1
1.Global context: "1. start"
- Step 2
2.Push placeOrder: "2. placeOrder"
- Step 3
3.Push pay (on top): "3. pay"
- Step 4
4.Pop pay, back in placeOrder: "4. back in placeOrder"
- Step 5
5.Pop placeOrder, back to global: "5. end"
Stack empty = program complete
9.7 Checkpoint: local shadows global
- Global x is 1; inside show() another var x = 2 comes after console.log.
- The local x is hoisted in the memory phase and hides the global x.
- At that moment the local x has no value yet, so it prints undefined (not 1, not 2).
var x = 1; function show() { console.log(x); var x = 2;} show();> undefined9.8 Common mistakes
- var inside a block: for a price of 500 discount stays undefined and the result is NaN.
- Fix: declare discount with let at the top of the function with 0, and only update it inside the if (output 500).
// Wrongfunction getPrice(price) { if (price > 1000) { var discount = 100; } return price - discount;}console.log(getPrice(500));// Rightfunction getPrice(price) { let discount = 0; if (price > 1000) { discount = 100; } return price - discount;}console.log(getPrice(500));- Thinking let is not hoisted: the local city is hoisted into the TDZ and hides the global city, so ReferenceError instead of Delhi.
let city = "Delhi"; function showCity() { console.log(city); let city = "Pune";} showCity();ReferenceError: Cannot access 'city' before initialization9.9 Rules
- const by default, let to reassign, no var.
- Declare variables at the top before using them, in the smallest scope where they are needed.
- Keep global variables to a minimum: any code can change them.
9.10 Interview tips
- Hoisting: before the code runs, JavaScript registers all declarations in the memory phase.
- var is initialized with undefined, function declarations are fully available, let / const stay in the TDZ until their line runs.
- This happens because of the memory phase of the execution context.
- The call stack holds execution contexts in LIFO order; scope lookup goes inside to outside.