Closures

In this lesson we will take a look at the interesting phenomenon that is closures. Let's begin!

You already learned that functions can return functions. This feature requires that functions have access to variables defined in another function’s scope.

Take a look at the Listing below. The code defines a createOp function that returns another function that uses the kind variable within its body. Although kind is declared in createOp, it is available later in the context of the returned function.

Listing: Accessing variables defined in another functions’ scope

<!DOCTYPE html>
<html>
<head>
  <title>Using closures</title>
  <script>
    var addOp = createOp("add");
    var subtractOp = createOp("subtract");

    console.log(addOp(23, 12));      // 35
    console.log(subtractOp(23, 12)); // 11

    function createOp(kind) {
      return function (a, b) {
        if (kind == "add") {
          return a + b;
        }
        else if (kind == "subtract") {
          return a - b;
        }
      }
    }
  </script>
</head>
<body>
  Listing 8-7: View the console output
</body>
</html>

In programming terminology, functions that do not have names are called anonymous functions.


Functions that have access to variables from other function’s scopes are called closures.


In the Listing above, the function returned from createOp is an anonymous function, and a closure, too.

To understand how this mechanism works, let’s focus on these code lines:

Press + to interact
var addOp = createOp("add");
// ...
console.log(addOp(23, 12)); // 35

When the createOp function is called, its execution context looks as shown in the image below.

The context contains two items in its scope chain, the activation object of ...

Access this course and 1400+ top-rated courses and projects.