JavaScript Closure

JavaScript Closure

A closure in JavaScript is a function that has access to the variables in its parent scope, even after the parent function has completed execution. This allows for data to be “closed over” or remembered by the inner function, even after the outer function has returned.

For example:

function makeCounter() {

  let count = 0;

  return function() {

    return count++;

  }

}

let counter = makeCounter();

console.log(counter()); // outputs 0

console.log(counter()); // outputs 1

console.log(counter()); // outputs 2

Here, the makeCounter function returns an inner function that has access to the count variable declared in its parent scope, and can “remember” the current count value even after the makeCounter function has completed execution. Each time the inner function is called, it returns the current value of count and increments it by 1.

const a = ‘hello’;

console.log(a);

abc();

function abc(){

   //const a = ‘world’;

   console.log(a);

}

function myCount(){

   let count = 0;

   return function(){

       return count++;

   }

}

function myCount2(){

   let count = 0 ;

   return count++;

}

let cnt = myCount();

let cnt2 = myCount2;

for(let x=0;x<10;x++){

   console.log(cnt());

   console.log(cnt2());

}

JavaScript Closure Advanced

In this example, the makeAdder function takes in a single argument x and returns an inner function that takes in a second argument y. The inner function has access to the x variable declared in the parent scope and uses it to add x and y together and return the result.

We can see here that the outer function makeAdder has been executed twice and it returns two different inner functions which are assigned to different variables add5 and add10 and these inner functions are able to remember their respective parent scope values of x.

function makeAdder(x) {

  return function(y) {

    return x + y;

  }

}

let add5 = makeAdder(5);

console.log(add5(3)); // outputs 8

console.log(add5(4)); // outputs 9

let add10 = makeAdder(10);

console.log(add10(5)); // outputs 15

console.log(add10(6)); // outputs 16

const output = document.querySelector(‘#output’);

function adder(val){

   return function(val2){

       return val + val2;

   }

}

let a1 = adder(15);

console.log(a1(2));

for(let x=0;x<10;x++){

  output.innerHTML += `<div>Output ${(a1(2+x))}</div>`;

}