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.
Further reading
Suggest a resource- javascript.info: Variable scope, closure(opens in a new tab)Lexical environments step by step, with the classic closure tasks.Articlejavascript.infoEditor’s pick
- javascript.info: The old "var"(opens in a new tab)How var differs from let and const in scope and hoisting.Articlejavascript.infoEditor’s pick
Test yourself on Closures and Scope
Ten questions, with the answer and explanation after each one.