Scope and Closures

Where a name is visible, why a function remembers the variables it was written next to, and how that single fact powers private state, memoisation, debouncing and every module pattern in JavaScript.

What you will be able to do

  • Explain lexical scope and trace how a name is resolved outward
  • Say precisely what a closure is, and what it captures
  • Build private state, a counter, a memoiser and a debouncer from scratch
  • Answer the var in a loop interview question correctly, and fix it three ways
  • Recognise the four common ways closures leak memory

Lessons

  1. Lexical Scope — Scope is decided by where you typed the code, not by who calls it. (12 min)
  2. Closures — A closure is a function that remembers the variables where it was written, not where it is called. (16 min)
  3. Closure Patterns in Real Code — Most utility functions you use daily are a closure with a good name. (16 min)
  4. Closures, Garbage Collection and Leaks — Memory is freed when nothing can reach it any more. A closure is something that can reach. (14 min)