Closures In Javascript

in simple words explain what are the closures in javascript with example.

Table of contents

No heading

No headings in the article.

A function bind together with it's lexical scope known as closures.

first, a fall let's understand what lexical scope means:-

lexical scope is a local memory along with it's parent's memory inorder or inhierarchy.

for example in the below code:-

inside function a() we are not having variable b, but when we call function a() we will get log 10, because when we invoke function a() the global execution context will be created and when we run line -> cosole.log(b) it will check is there variable b available in local memory of function a() execution context. after not finding out , it will get from it's lexical environment and that is it's parent memory.this is how lexical scope works.

function a(){
console.log(b);
}
var b = 10 ;
a();

let's come back again to the closures:-

let's take an exaple where we have created function y() and function x() .

and we have invoked function x() with the help of variable Z , when our variable Z will be invoked excution context of x will be created where a memory will be allocated to variable a as 10. and after that line execution context of x is deleted from callstack . and function y is returned but in reality, only function y is not returned closure was return, remember function with it's lexical scope . so still it will remember the reference to variable a.

as we call z() it will check is a available in function y() local memory if not then it will check it's lexical scope and will print 10.

function x(){
var a = 10;
function y(){
console.log(a);
}
return y;
}
var Z = x();
Z();

remember function with it's lexical scope known as closures. even after deletion of the execution context of it's parent function from callstack function remembers reference to a variable.