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.
To run the program, save it as closures.js
and use Node.js:
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.