SkillPilotAI

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.
JavaScript
function getPrice(price) {  if (price > 1000) {    var discount = 100;  }  return price - discount;} console.log(getPrice(1500));console.log(getPrice(500));
Output
> 1400> NaN

9.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.
JavaScript
const shop = "Flipkart"; function checkout() {  const user = "Riya";   if (user) {    const coupon = "SAVE10";    console.log(shop, user, coupon);  }   console.log(coupon);} checkout();
Output
> Flipkart Riya SAVE10ReferenceError: coupon is not defined

9.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.
Scope chain lookup
  1. 1.Block scope: coupon

  2. 2.Not here? Function scope: user

  3. 3.Not here? Global scope: shop

  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.
JavaScript
console.log(city);var city = "Pune"; greet();function greet() {  console.log("Hi from greet");} console.log(pin);let pin = 411001;
Output
> undefined> Hi from greetReferenceError: Cannot access 'pin' before initialization
DeclarationHoisted?Value before its lineScope
varYesundefinedFunction
letYesTDZ: ReferenceErrorBlock
constYesTDZ: ReferenceErrorBlock
function declarationYes, with full codeCallableFunction
const arrow / expressionLike constTDZ: ReferenceErrorBlock

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.
2 phases of an execution context
  1. 1.Context created (program start or function call)

  2. 2.Memory phase: var = undefined

  3. 3.Memory phase: functions = full code, let / const = TDZ

  4. 4.Execution phase: run line by line

  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.
JavaScript
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");
Output
> 1. start> 2. placeOrder> 3. pay> 4. back in placeOrder> 5. end
Call stack: LIFO
  1. 1.Global context: "1. start"

  2. 2.Push placeOrder: "2. placeOrder"

  3. 3.Push pay (on top): "3. pay"

  4. 4.Pop pay, back in placeOrder: "4. back in placeOrder"

  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).
JavaScript
var x = 1; function show() {  console.log(x);  var x = 2;} show();
Output
> undefined

9.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).
JavaScript
// Wrongfunction getPrice(price) {  if (price > 1000) {    var discount = 100;  }  return price - discount;}console.log(getPrice(500));
JavaScript
// 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.
JavaScript
let city = "Delhi"; function showCity() {  console.log(city);  let city = "Pune";} showCity();
Output
ReferenceError: Cannot access 'city' before initialization

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