Closures

In JavaScript, a closure is a function that has access to variables defined outside of its own scope, even after those variables have gone out of scope. This is possible because when a function is created, it forms a closure with the environment in which it was created, and it retains a reference to that environment.

Let's see an example:

Loading Code . . .

In the above example, we define a function called createCounter that returns a function. The function returned by createCounter is a closure. It has access to the variable count defined in the outer function, even after the outer function has returned.

Each time we call counter1, the value of count is incremented by 1, and the new value is printed to the console.

In other words, the closure remembers the environment in which it was created, and it retains a reference to that environment and the variables defined in that environment.

Closures are useful in a variety of situations that we will explore in the next few chapters.

Code Challenge

Write a function called fibonacciGenerator that returns a function that each time it is called returns the next number in the Fibonacci sequence.

The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the previous two numbers: 1, 1, 2, 3, 5, 8, ...

Loading...
Loading...
Loading...

© 2024 - ®Mewters