Javascript Closures (ES6 EcmaScript2015)
Nov 21, 2018
Closure: A closure is the combination of a function and the lexical environment within which that function was declared.
In simple words closure are functions within function or functions inside another function
All the variables or properties of parent function are visible in child functions: say in below example name variable of parent function myFun() is visible inside child function i.e inside displayName()
Closure Basic program:
Example1:
function myFun() {
var name = “ankit”;
function displayName() {
console.log(name);
}
displayName();
}// Calling closure function
myFun(); //output :ankit
Example2:
// Closure same example with different approachfunction func() {
var name = “ankit kamboj”;
function displayName() {
console.log(name);
}
return displayName;
}// Calling closure function
func()();//output: ankit kamboj
Example3:
function makeAdder(x) {
return function (y) {
return x + y;
}
}console.log(makeAdder(5)(2)); //output:7
console.log(makeAdder(10)(2)); //output:12
Conclusion
This is it , a bit smaller module but assume will have given a basic understanding about the concept.
For more follow:
Thanks for your time, Have a great Time Cheers..!!