Closures in JavaScript

JavaScript supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

// This function intSeq returns another function, which
// we define anonymously in the body of intSeq. The
// returned function closes over the variable i to
// form a closure.
function intSeq() {
    let i = 0;
    return function() {
        i++;
        return i;
    };
}

// We call intSeq, assigning the result (a function)
// to nextInt. This function value captures its
// own i value, which will be updated each time
// we call nextInt.
const nextInt = intSeq();

// See the effect of the closure by calling nextInt
// a few times.
console.log(nextInt());
console.log(nextInt());
console.log(nextInt());

// To confirm that the state is unique to that
// particular function, create and test a new one.
const newInts = intSeq();
console.log(newInts());

To run the program, save it as closures.js and use Node.js:

$ node closures.js
1
2
3
1

In this JavaScript version, we define the intSeq function that returns an anonymous function. This anonymous function forms a closure, capturing the i variable from its outer scope.

We then demonstrate the use of this closure by calling intSeq() and assigning the returned function to nextInt. Each time we call nextInt(), it increments and returns its own private i variable.

Finally, we create a new closure by calling intSeq() again and assigning it to newInts. This demonstrates that each closure has its own independent state.

Closures are a powerful feature in JavaScript, often used for data privacy, function factories, and in functional programming patterns.