liveBook · Manning

Closure

As explained in Functional Programming in JavaScript

A function together with the lexical environment in which it was created, enabling access to captured variables after the outer scope has finished executing.

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

How Functional Programming in JavaScript covers it

How deep it goes
Defines lexical capture and demonstrates nested functions, name resolution, function factories, and closure-backed objects.
Examples
Uses nested functions, a zipCode accessor object, function factories, callback syntax, and an ambiguous loop-counter example.
What it assumes
Assumes basic JavaScript functions and variables while teaching lexical scope, nested functions, and outward name resolution.
What you can do after
Apply it via JavaScript functions that retain parameters and enclosing variables after their outer calls finish.
How it connects
Connects closures with lexical scope, scoping rules, higher-order functions, callbacks, event handling, and private variables.

Also explained in

Compare how 20 books explain closure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.