Closure in JavaScript

Closure in JavaScript

Closure :

Closures in JavaScript are like small memory bubbles that remember the environment in which they are created. This means you can create a function that remembers and accesses the data from the parent function even when the parent function is no longer running. It's a way to store and use information that would normally be forgotten once a function completes its job.

In simpler terms, closures help you keep data private and organized within your function. learnmore

Example:

// example

function outerFunction(x) {

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

//creating a  closure by calling outer function

const closure = outerFunction(10); // pass the x parameter with value 10

// Now we can use closure to add 5 to the remembered x

const result = closure(5);
console.log(result); // result will be 15

Here's a breakdown of what's happening in the code:

  1. outerFunction is defined, which takes a parameter x.

  2. Inside outerFunction, another function innerFunction is defined, which takes a parameter y and returns the sum of x (from the outer scope) and y.

  3. outerFunction then returns innerFunction.

  4. When we call outerFunction with 10, it returns innerFunction, creating a closure where x is remembered as 10.

  5. we store this closure in the variable closure.

  6. Later, we call closure with 5, which adds 5 to the remembered value of x (which is 10), resulting in 15.


Thank You For Reading