Closure-JavaScript

Mohammad Salman
2 min readFeb 6, 2021

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

function alpha() {

let lion = “lion”;

return function beta() {

let tiger = “tiger”;

return function gamma() {

let wolf = “wolf”;

return `${lion} > ${tiger} > ${wolf}`

}

}

}

alpha()()()

O/P:- lion > tiger > wolf

When we called function alpha(), it’s added to the Call Stack, similarly beta() and gamma(). what happened when all function popped up from call stack and removed variable environment.

somehow function gamma() has access alpha() and beta() functions 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 alpha() {

let lion = “lion”;

return function beta() {

let tiger = “tiger”;

let random = 12345;

return function gamma() {

let wolf = “wolf”;

return `${lion} > ${tiger} > ${wolf}`

}

}

}

random 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 until 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.

--

--

Mohammad Salman

Learner | Software Engineer | JavaScript | TypeScript | ReactJS| NextJS | NodeJS