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
1/*A closure is the combination of a function bundled together (enclosed) with references
2to its surrounding state (the lexical environment). In other words, a closure gives you
3access to an outer function’s scope from an inner function. In JavaScript, closures are
4created every time a function is created, at function creation time.*/
5
6function init() {
7 var name = 'Mozilla'; // name is a local variable created by init
8 function displayName() { // displayName() is the inner function, a closure
9 alert(name); // use variable declared in the parent function
10 }
11 displayName();
12}
13init();
14
1function OuterFunction() {
2
3 var outerVariable = 1;
4
5 function InnerFunction() {
6 alert(outerVariable);
7 }
8
9 InnerFunction();
10}
11