It allows a function to access variables from a enclosing scope or environment even after it leaves the scope in which it was declared.

function democracy() {

let india = “india”;

return function usa() {

let america = “america”;

return function sauth() {

let africa = “africa”;

return `${india} > ${america} > ${africa}`

}

}

}

democracy()()()

// india > america > africa

When we called function democracy(), it’s added to the Call Stack, similarly usa and sauth. what happend when all function popped up from call stack and removed variable environment.

somehow function africa has access democracy and usa function variables. this is what closure is.

Closure is something called small box where after function popped up from Call Stack. their variable is store in the closure box because that variables reference in somewhere other function. JavaScript engine make sure that the function has access to the variables outside of the function with help of closure.

function democracy() {

let india = “india”;

return function usa() {

let america = “america”;

let randome = 12345;

return function sauth() {

let africa = “africa”;

return `${india} > ${america} > ${africa}`

}

}

}

randome variable is going to be in garbage collectors because nothing referencing it.

Lexical Scope:- Where it written

Scope:- What variable we have access to.

where we write the function is matter, not where we call the function.

function show() {

const me = “I am salman!”;

setTimeout(() => {

console.log(me);

},4000)

}

show()

After done with setTimeout in web API, it send completed data to the callback queue and callback queue is going to wait there untill the Call Stack is empty. so show function has been called, it’s now popped up from Call Stack and event loop is going to push the data from callback queue to the Stack and run and it’s going to console.log(me).

But variable ‘me’ should have gone because function show has been popped up from Stack by the time console.log(me) run.

But because of Closure even if some of the function is going out to the web API world, we are able to remember variable because of Closure.

Software Engineer. Open Source Enthusiastic