liveBook · Manning

Closure

As explained in The Joy of JavaScript

A function together with the lexical environment in which it was created, allowing it to retain access to enclosed bindings.

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

How The Joy of JavaScript covers it

How deep it goes
Defines lexical retention and [[Scope]], illustrates nested access, and applies closures to currying without pursuing specification-level internals.
Examples
Uses nested scope logging and a deferred assemble function that captures keys before receiving an object.
What it assumes
Assumes familiarity with JavaScript functions and scope while reinforcing nested lexical access through small examples.
What you can do after
Evaluate/understand closures well enough to create deferred functions, apply currying, and bound captured state for maintainable composition.
How it connects
Connects closures with lexical scope, higher-order functions, currying, composition, pure functions, and side effects.

Also explained in

Compare how 20 books explain closure →

Related concepts

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