A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). A closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
function a(){
let name = "TIM";
return function b(){
let email ="email@gamil.com";
return function c(){
let phone ="647-000-000";
return console.log(`${name} ${email} ${phone}`);
}
}
}
a()()();
TIM email@gamil.com 647-000-000
function c have access to name and email variable.
Again, A closure gives you access to an outer function’s scope from an inner function.
Even if the function a() gets removed off the stack but name still remains in memory heap.
The garbage collector can not clean up because there is something that is referencing name from inside of function a(). Which means any functions has access to all of the variables outside of the function with closures.
Closures are also called lexical scoping
.
function callMeMaybe(){
setTimeout(function(){
console.log(callMe)
}, 4000)
}
const callMe = "Hi";
callMeMaybe()
Improve memory efficient with closures.
function heavyDuty(i){
const bigArray = new Array(500).fill("U");
console.log("Big Array is Created!");
return console.log(bigArray[i]);
}
heavyDuty(123)
heavyDuty(124)
heavyDuty(125)
Big Array is Created!
U
Big Array is Created!
U
Big Array is Created!
U
big Array is created three times. This is not efficient.
function heavyDutyWithClosures(){
const bigArray = new Array(500).fill("U");
console.log("Big Array is Created!");
return function(i){
return console.log(bigArray[i])
}
}
const closuresHeayDuty = heavyDutyWithClosures()
closuresHeayDuty(123)
closuresHeayDuty(124)
closuresHeayDuty(125)
Big Array is Created!
U
U
U
big Array is created one time.
Closure concept is now adopted and added to different language like python, Ruby
, C#
, and c++
also adding closures to their language.
More example)
let view;
function initialize(){
let called = 0;
return function (){
if (called > 0){
return;
}
else{
console.log("view has been set");
view = "*";
called = 1;
}
}
}
const init = initialize();
init()
init()
init()
console.log(view);
view has been set
*