A closure is a function together with the lexical environment around it. JavaScript retains references to surrounding variables, so the function can use bindings from outer and global scopes even after it is created. section 4.4
Closures matter because they:
- Connect a function to its internal [[Scope]] reference, also called its backpack. section 4.4
- Make surrounding state behave like implicit function arguments, including variables declared in outer scopes and hoisted bindings. section 4.4
- Enable higher-order patterns such as currying, where a function captures earlier arguments and returns another function. section 4.4 section 4.3.2
- Remain easiest to maintain when their scope is narrow and they cause no observable changes beyond the enclosed function. section 4.4
Capturing keys for later use
function assemble(keys) { return function(obj) { return keys.map(f => obj[f]).join(''); }; } assemble captures keys when called, then returns a function that accepts obj later. The returned function uses both its immediate argument and the captured binding, allowing the operation to participate in a composed calculation. section 4.3.2
Listing 4.8 Basics of scope with closures
const global = 'global';
function outer() {
const outer = 'outer';
function inner() {
const inner = 'inner'
console.log(inner, outer, global); #1
}
console.log(outer, global); #2
inner();
}
outer();
Trace how inner can access inner, outer, and global bindings, while outer can access its own and global scope. section 4.4



















