1// closure in javascript
2-> A closure gives you access to an outer function’s scope
3 from an inner function
4
5const outerFun = (a) => {
6 let b = 10;
7 // inner func can use variable/parameter of outer funcion
8 const innerFun = () => {
9 let sum = a + b;
10 console.log(sum);
11 }
12 return innerFun;
13}
14let inner = outerFun(5);
15inner();
1A closure gives you access to an outer function’s scope from an inner function
2//example
3function init() {
4 var name = 'Mozilla'; // name is a local variable created by init
5 function displayName() { // displayName() is the inner function, a closure
6 alert(name); // use variable declared in the parent function
7 }
8 displayName();
9}
10init();
11
1function makeAdder(x) {
2 return function(y) {
3 return x + y;
4 };
5}
6
7var add5 = makeAdder(5);
8var add10 = makeAdder(10);
9
10console.log(add5(2)); // 7
11console.log(add10(2)); // 12
1function outer() {
2 var counter = 0; // Backpack or Closure
3 function incrementCounter() {
4 return counter++;
5 }
6 return incrementCounter;
7}
8
9const count = outer();
10count(); // 0
11count(); // 1
12count(); // 2
1function OuterFunction() {
2
3 var outerVariable = 100;
4
5 function InnerFunction() {
6 alert(outerVariable);
7 }
8
9 return InnerFunction;
10}
11var innerFunc = OuterFunction();
1//Closures are the inner functions that are embedded in parent function
2function getName(){
3 // print name function is the closure since it is child function of getName
4 function printName(){
5 return 'Kevin'
6 }
7 // return our function definition
8 return printName;
9}
10
11const checkNames = getName();
12console.log(checkNames());