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
A closure is a function plus the variables it can reach from where it was defined, even after the outer function returns.
- 2
varis function-scoped and hoisted asundefined;letandconstare block-scoped and sit in a temporal dead zone until declared. - 3
Closures in a
varloop share one variable;letgives each iteration its own binding. - 4
Factories (functions returning functions) use closures to keep private state, like a counter.
Common traps
Reading a
letvariable before its declaration throws a ReferenceError; reading avargivesundefined.
Test yourself on Closures and Scope
Ten questions, with the answer and explanation after each one.