forked from bittu1040/JavaScript-Coding-and-Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClosure.js
72 lines (50 loc) · 1.43 KB
/
Closure.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// closure in JS
// Function along with its lexical scope bundled together forms a closure.
// Closure is a combination of a function bundled together with its surrounding state. (lexical environment)
// A closure gives you access to an outer function's scope from an inner function. (this means inner function will have access to outer function's scope)
//example
/*
function x() {
var a = 8;
var a = 100;
function y() {
console.log(a);
}
return y;
}
var z = x();
z();
*/
// example 1
// change the let and var in for loop and see the result. you will understand the difference between block scope and global scope.
// let and const is blocked scope, so loop jitna bar chlta hai, every time ek block create hota hai jisme settimeout store rhta hai aur usme i ka value store rhta hai.
// var keyword jb hm use krte hain, wo block scope nhi hota hai, is time i ka value global scope me update hota jata hai, isliye last me hmko 6 milta hai jhan pe for loop stop hota hai.
/*
function y() {
for(let i=1; i<=5; i++){
setTimeout(() => {
console.log(i)
}, i * 1000);
}
console.log("bittu")
}
y();
*/
// example 2
function outer(){
var a=20;
function inner(){
console.log(a)
}
return inner;
}
var a=10;
console.log(a);
outer()();
// example 3
function test1(x){
return function test2(y){
return x+y;
}
}
console.log(test1(2)(3))