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();
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
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
12
13//=====
14//add5 and add10 are both closures.
15//They share the same function body definition, but store different lexical environments.
16//In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.
17