JavaScript Closure

JavaScript Closure Explained

A closure in JavaScript is a function that has access to variables in its parent scope, even after the parent function has returned. Closures are created when a function is defined inside another function, and the inner function retains access to the variables in the outer function’s scope.

Here is an example of a closure in JavaScript:

code example

function outerFunction(x) {

    var innerVar = 4;

    function innerFunction() {

        return x + innerVar;

    }

    return innerFunction;

}

var closure = outerFunction(2);

console.log(closure()); // Output: 6

In this example, the innerFunction is a closure because it has access to the variable x and innerVar from the outerFunction even after outerFunction has returned.

A closure has three scope chains:

  1. It has access to its own scope (variables defined between its curly braces {}).
  2. It has access to the outer function’s variables.
  3. It has access to the global variables.

Closures are commonly used in JavaScript for a variety of tasks, such as:

  • Implementing private methods and variables.
  • Creating callback functions that retain access to variables from their parent scope.
  • Creating and returning an object that has access to variables from its parent scope.

JavaScript closures are an important concept and it is important to understand how closures work in JavaScript. It is also important to be aware of the scope chain, and how closures interact with the scope chain.