To Simply say, Closure is a feature of a function that allows it to remember all the variables in its lexical scope even after the execution of the function. For an example, When when fire event to access from the DOM , that is also Closure.

Lets a program first.

function add(a) {
  return function (b) {
    return a + b;
  };
}

let addTen = add(10);
let addNine = addTen(9);

console.log(addNine); <em>// 19</em>

What is happening there ? lets break.

  • We called a function add and this function returned another function inside.
  • Now when the function run and finished in addTen variable, it will keep remember the value of a.
  • so now we will pass another value 9 as function parameter into AddTen object.
  • Now we can see the value is 19.

Interesting ! so how this is happened ? The Magic is When run AddTen function that looks like.

function addTen(b) {
  return 10 + b;
}

Lets see another example to clear more. We will try count something

function counter(){
	let count = 0;
  return function (counter){
    return count = count+1;
  }
}
let getcounter = counter();

console.log(getcounter()); <em>//1</em>
console.log(getcounter()); <em>//2</em>
console.log(getcounter()); <em>//3</em>

Now you can see getcounter always keep remeber the count value and do the inside function operation when you call it.