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 OuterFunction() {
2
3 var outerVariable = 100;
4
5 function InnerFunction() {
6 alert(outerVariable);
7 }
8
9 return InnerFunction;
10}
11var innerFunc = OuterFunction();
1function makeFunc() {
2 var name = 'Mozilla';
3 function displayName() {
4 alert(name);
5 }
6 return displayName;
7}
8
9var myFunc = makeFunc();
10myFunc();
11
1var makeCounter = 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
19var counter1 = makeCounter();
20var counter2 = makeCounter();
21alert(counter1.value()); /* Alerts 0 */
22counter1.increment();
23counter1.increment();
24alert(counter1.value()); /* Alerts 2 */
25counter1.decrement();
26alert(counter1.value()); /* Alerts 1 */
27alert(counter2.value()); /* Alerts 0 */
28
1// global scope
2var e = 10;
3function sum(a){
4 return function(b){
5 return function(c){
6 // outer functions scope
7 return function(d){
8 // local scope
9 return a + b + c + d + e;
10 }
11 }
12 }
13}
14
15console.log(sum(1)(2)(3)(4)); // log 20
16
17// You can also write without anonymous functions:
18
19// global scope
20var e = 10;
21function sum(a){
22 return function sum2(b){
23 return function sum3(c){
24 // outer functions scope
25 return function sum4(d){
26 // local scope
27 return a + b + c + d + e;
28 }
29 }
30 }
31}
32
33var sum2 = sum(1);
34var sum3 = sum2(2);
35var sum4 = sum3(3);
36var result = sum4(4);
37console.log(result) //log 20
38