Defination by javascript
Closure in Javascript refers to the conbination of a function and the lexical enviroment in which it declared. It allows a function to access variables and data from its outer scope, even after the outer function has finished executing.
In Other words, when a function is defined inside another function, the inner function retains access to the variables, parameters and function of it's parent function, even after the parent function has completed execution. This access to the outer scope is made possible by the closure.
Apni defination
Hindi main bolu to muje kya samaj ayaa ki agar hum ek function ke undar koi dusara function banaye to hum bahar(outer) wale function ke variabe ko bhi use kar sakte hai vo variable ya data destroy nahi hoga uska access hamesha undar(inner) wale function ko milega. To Chalo niche kuch Example dekhe:-
In This example you can see inner function access the variable which is declared in outer function.
1 function outerFun() {
2 var name = "Shivraj";
3 function innerFun() {
4 console.log(name);
5 }
6 innerFun();
7 }
8 outerFun(); // Output will be "Shivraj"
In This example outer function (outerFun) return a inner fun (innerFun) which is stored in store variable.
1 function outerFun() {
2 const blog = "Closure in JavaScript";
3 function innerFun() {
4 console.log(name);
5 }
6 return innerFun;
7 }
8
9 const store = outerFun();
10 console.log(store()) // output wiil be "Closure in JavaScript" ;
In This example makeAdder function return a anonymous function which is stored in add1 and add2 variables and final output is (parameter passed in outer function + parameter passed in inner function)
1 function makeAdder(x) {
2 return function (y) {
3 return x + y;
4 };
5 }
6
7 const add1 = makeAdder(5);
8 const add2 = makeAdder(10);
9
10 console.log(add1(12)); // 17
11 console.log(add2(11)); // 21" ;
In This example when we call sum function then it returns top level inner function and now we can access it by calling sum(), like = sum()().
1 // global scope
2 const e = 10;
3 function 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
15 console.log(sum(1)(2)(3)(4)); // 20
In This example we are storing inner function one by one and when last function is (sum4) called it return the sum of all parameters passed in functions.
1 function sum(a) {
2 return function sum2(b) {
3 return function sum3(c) {
4 return function sum4(d) {
5 return a + b + c + d + e;
6 };
7 };
8 };
9 }
10
11 const sum2 = sum(1);
12 const sum3 = sum2(2);
13 const sum4 = sum3(3);
14 const result = sum4(4);
15 console.log(result); // 20