Study notes · 13% of the exam

Closures and Scope

Functions remember the scope they were created in. Understand block scope, hoisting and the classic loop bug.

Key points

  1. 1

    A closure is a function plus the variables it can reach from where it was defined, even after the outer function returns.

  2. 2

    var is function-scoped and hoisted as undefined; let and const are block-scoped and sit in a temporal dead zone until declared.

  3. 3

    Closures in a var loop share one variable; let gives each iteration its own binding.

  4. 4

    Factories (functions returning functions) use closures to keep private state, like a counter.

Common traps

  • Reading a let variable before its declaration throws a ReferenceError; reading a var gives undefined.

Read the source

Test yourself on Closures and Scope

Ten questions, with the answer and explanation after each one.