← Back to Engine

Hoisting & Lexical Scope


In Javascript, variable and function declarations are moved to the top of their scope during the creation phase.

hoisting explanation

1. var Hoisting vs let/const (TDZ)

  • var: Hoisted and initialized with undefined. Accessible prior to declaration without crashing!
  • let / const: Hoisted into memory, but left uninitialized in the Temporal Dead Zone (TDZ). Accessing them before declaration throws a ReferenceError.

2. Function Declarations vs Expressions

  • function foo() {} (Declaration): Entire function definition is hoisted and fully invocable before its declaration.
  • var foo = function() {} (Expression): Only the variable name foo is hoisted (as undefined). Invocations prior to assignment throw TypeError: foo is not a function!

3. Block Scope & Variable Pollution

var ignores block boundaries like if statements and for loops, leaking variables to the outer function/global scope. let and const enforce strict block scoping inside { ... }.


The Challenge: Scope & TDZ Analysis

Implement scopeChallenge() to demonstrate your understanding. It must return an object containing:

  1. hoistedVar: The value of a var variable captured before its initialization (should be undefined).
  2. tdzHandled: A boolean set to true by catching the ReferenceError when attempting to access a let variable in its TDZ inside a try/catch block.
  3. loopResult: The sum of numbers 0 through 9 calculated using a block-scoped let loop variable (sum = 45).