Learn  closure  in JavaScript with code

Learn closure in JavaScript with code

In JavaScript, a closure is a combination of a function and the lexical environment within which that function was declared. This lexical environment consists of the variables that were in scope at the time the closure was created. In simpler terms, a closure allows a function to access variables from its outer (enclosing) scope even after the outer function has finished executing.

Here's a basic example to illustrate the concept of a closure:

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

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

  return innerFunction;
}

// Create a closure by calling outerFunction and assigning its result to a variable
let closure = outerFunction();

// Call the closure, which still has access to outerVariable
closure(); // Output: "I am from the outer function"

In this example, outerFunction defines a variable called outerVariable and declares an inner function called innerFunction. When outerFunction is invoked, it returns innerFunction, creating a closure. Even after outerFunction has finished executing, the closure (assigned to the variable closure) retains access to outerVariable. When you call closure(), it logs the value of outerVariable to the console.

Closures are powerful and commonly used in JavaScript for various purposes, such as creating private variables, implementing data hiding, and managing state in functional programming patterns. They play a crucial role in creating modular and maintainable code.

✨Thank you for taking the time to read this captivating content.