How do JavaScript closures work?

How do JavaScript closures work?

In JavaScript, a closure is a function that has access to the variables of its outer function, even after the outer function has returned.

Here’s an example of a closure in JavaScript:

function outerFunction(x) {
  return function innerFunction(y) {
    return x + y;
  }
}

const addFive = outerFunction(5);
console.log(addFive(10)); // 15
console.log(addFive(20)); // 25

In this example, the inner function innerFunction is a closure because it has access to the x variable of the outer function outerFunction, even after outerFunction has returned.

The innerFunction function retains the environment in which it was created, which is known as a closure. This means that the innerFunction function has access to the variables in the environment, even after the outer function has returned.

Closures are useful because they allow you to create functions with private variables. The inner function can access the private variables of the outer function, but the outer function’s variables cannot be accessed from the outside.

Here’s an example of a closure with private variables:

function counter() {
  let count = 0;
  return function increment() {
    count++;
    return count;
  }
}

const myCounter = counter();
console.log(myCounter()); // 1
console.log(myCounter()); // 2

In this example, the count variable is private to the counter function because it is defined inside the function. The increment function, which is returned by the counter function, is a closure that has access to the count variable. However, the count variable is not accessible from the outside.

Leave a Reply