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();
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 makeFunc() {
2 var name = 'Mozilla';
3 function displayName() {
4 alert(name);
5 }
6 return displayName;
7}
8
9var myFunc = makeFunc();
10myFunc();
11
1var counter = (function() {
2 var privateCounter = 0;
3 function changeBy(val) {
4 privateCounter += val;
5 }
6 return {
7 increment: function() {
8 changeBy(1);
9 },
10 decrement: function() {
11 changeBy(-1);
12 },
13 value: function() {
14 return privateCounter;
15 }
16 };
17})();
18
19console.log(counter.value()); // logs 0
20counter.increment();
21counter.increment();
22console.log(counter.value()); // logs 2
23counter.decrement();
24console.log(counter.value()); // logs 1
25