Functions, Scope and Closures

Learn lexical scope, hoisting and closures: the mechanics behind callbacks, hooks, event handlers and module privacy.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Types, Coercion and Equality

Closures are the single most important "deep" JavaScript concept for frontend developers. React hooks, event handlers, debounce utilities and module patterns all rely on them.

Scope

  • Lexical scope: a function can see variables from where it was written, not where it is called.
  • let and const are block scoped (inside {}); var is function scoped.
  • Hoisting: declarations are processed before code runs. Function declarations are fully hoisted; let/const exist in a "temporal dead zone" until their line runs, so accessing them early throws.

Closures

A closure is a function bundled with the variables it references from its outer scope. Those variables stay alive as long as the function does.

  • A counter factory: makeCounter() returns a function that increments a private count.
  • A debounce(fn, ms) helper remembers its timer between calls.
  • In React, a stale closure happens when an effect or callback captured an old value of state and never sees the new one.

Higher-order functions

Functions are values: they can be passed in (callbacks) and returned (factories). map, addEventListener and setTimeout all take functions. Currying and partial application build on the same idea.

Classic pitfall

A for (var i ...) loop that schedules timeouts logs the final value every time, because there is one shared i. With let, each iteration gets its own binding.

Move on when you can implement debounce, once and a memoize helper from scratch and explain what each closure holds on to.

Key concepts

  • Lexical scope
  • Block vs function scope
  • Hoisting and the temporal dead zone
  • Closures
  • Higher-order functions and callbacks
  • Stale closures: Shows up constantly in React
  • Currying and partial application
  • IIFE and the module pattern

Mini project

Write a tiny utility library with debounce, throttle, once and memoize, plus a demo page where a search box uses your debounce to limit simulated API calls.

Check yourself

Why does a loop using var print the same number from every setTimeout callback, while let does not?

Free resources