DEV Community

Nikita Maharana
Nikita Maharana

Posted on

Closure Explained in JS

Closure: An inner fxn remembers the outer fxn values even after outer fxn execution gets ended.

We use this in techniques called memorization it means making code able to remember the previous input and its corresponding output such that it will not again calculate for same input.

//CLosure
function outer(){
var x = 25;
function inner() {
x++;//x is not in inner fxn its in outer but it remembers outer value that called memorization or closure
console.log(x);
}
return inner;
}
let result = outer();
console.log(result);
//it calls outer and outer returns inner so whole innner fxn returns
//inner is not yet called so 26 will not be printed as it is seems

result();//inner called 26
result()//27
result()//28 and so on...

Top comments (0)