-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotes.txt
More file actions
55 lines (41 loc) · 2.14 KB
/
Notes.txt
File metadata and controls
55 lines (41 loc) · 2.14 KB
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
Closure in Java Script
Closure is a feature in java Script where Inner function can Access has an Outer function variable.
Closure has three Scope chains
1.It can access its own variable( the variable within the curly brackets).
Example:
function outer(){ //creating parent function called outer
let count=0;
function inner(){ //creating a child function called inner
count++; //counting
console.log(count);
}
return inner; // returning function itself
}
let result=outer(); //return value and assignment and function call
result(); //function call at first time
result(); // function call at second time
let y =outer(); //assigning again to outer function
y(); // function with another variable
2. It can access parent variables which are outer function variables.
Example:
function outer(){ //creating parent function called outer
let a=10;.
function inner(){ //creating a child function called inner
let b=20;
return a+b; // access a from outside of the function(outer)
}
return inner; // returning function itself
}
let result=outer(); //return value and assignment and function call
console.log(result()); // print 30 has output
3. It also can access Global variables.
Example:
let globalVar = 100; // global variable
function outer() {
function inner() {
console.log(globalVar); // accesses global variable
}
return inner; // inner survives outside → closure
}
let fn3 = outer();
fn3();