1. javascript
  2. /closures

JavaScript Closures

A JavaScript closure is a function that has access to the variables and functions defined in outer scopes even after the outer function has returned. This is possible because the closure retains a reference to the outer scopes, allowing the inner function to access and modify the variables in the outer scopes even after the outer function has finished executing.

Here is a simple example of a closure in JavaScript:

function outerFunction() {
  var outerVariable = "Hello, ";

  return function innerFunction() {
    // The inner function has access to the outerVariable
    // even after the outerFunction has returned
    return outerVariable + "world!";
  }
}
var closure = outerFunction();
console.log(closure()); // prints "Hello, world!"

In this example, the outerFunction defines a variable outerVariable and returns an anonymous function (the innerFunction) that has access to the outerVariable. When the outerFunction is called, it returns the innerFunction, which is stored in the variable closure. When we call the closure function, it is able to access the outerVariable and prints the expected output.

Closures are useful because they allow you to create functions that can access variables and functions defined in outer scopes even after those outer functions have returned. This can be useful for creating functions that have access to certain state that is not accessible to the global scope, or for creating functions that have private variables that cannot be modified from outside the function.