🍠What is a closure

A closure in JavaScript is a function that has access to the variables in its outer (enclosing) function's scope even after the outer function has returned. This is possible because the inner function maintains a reference to the environment in which it was created, which includes the variables of the outer function.

Here is an example of a closure in JavaScript:

function outerFunction() {
  let outerVariable = 'I am the outer variable';

  return function innerFunction() {
    console.log(outerVariable);
  }
}

let closure = outerFunction();
closure(); // logs 'I am the outer variable'

In this example, the innerFunction has access to the outerVariable variable even after the outerFunction has returned. This is because the innerFunction maintains a reference to the environment in which it was created, which includes the outerVariable variable. When we call the closure function, it logs the value of outerVariable.

Closures are often used to create private variables in JavaScript. They can also be used to create higher-order functions, which are functions that take other functions as arguments or return functions as their result.

Last updated