0Pricing
JavaScript Academy · Lesson

Block/Function/Module Scope and the TDZ

Understand block, function, and module scope; see TDZ in action and avoid leaking variables.

Intro

Goal: Know where variables live and when they are usable.

  • Block scope (let/const)
  • Function scope (var)
  • Module scope
  • TDZ safety
Block/Function/Module Scope and the TDZ — illustration 1

Block scope demo

Block scope keeps variables local to a pair of braces.

// Block scope: let/const exist only inside the braces
let lives = 3;

if (true) {
  const bonus = 5;
  let level = 1;
  console.log("Inside block:", bonus, level);
}

console.log("Lives:", lives);
// Uncommenting next line would fail (not in scope):
// console.log(bonus, level);
Block/Function/Module Scope and the TDZ — illustration 2

All lessons in this course

  1. let, const, and avoiding var
  2. Block/Function/Module Scope and the TDZ
  3. Naming, Readability, and Common Pitfalls
← Back to JavaScript Academy