A closure lets a function keep using variables from the scope where it was created, even after that outer function finishes. This preserves useful state for callbacks, higher-order functions, private variables, and event handling. section 2.4
A function remembers its environment
function makeInner(params) { var innerVar = 'Inner'; function inner() { console.log(`I can see: ${outerVar}, ${innerVar}, and ${params}`); } return inner; } var outerVar = 'Outer'; var inner = makeInner('Params'); inner(); // 'I can see: Outer, Inner, and Params' Although makeInner has finished, inner still accesses outerVar, innerVar, and params. section 2.4
Closures support several practical patterns:
- Preserve data behind functions that expose selected operations. section 2.4
- Create specialized functions by capturing arguments such as an amount or base. section 2.4
- Use lexical name resolution, which searches the local scope and then enclosing scopes. section 2.4
function zipCode(code, location) {
let _code = code;
let _location = location || '';
return {
code: function () {
return _code;
},
location: function () {
return _location;
},
...
};
}
Inspect a zipCode object whose returned methods retain access to code and location values after zipCode returns. section 2.4



















