You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Task 1: Write a function that returns another function, where the inner function accesses a variable from the outer function's scope. Call the inner function and log the result.
4
+
5
+
functionouterFunction(){
6
+
letouterVariable="I'm from outer function";
7
+
8
+
functioninnerFunction(){
9
+
console.log(outerVariable);
10
+
}
11
+
12
+
returninnerFunction;
13
+
}
14
+
15
+
constinner=outerFunction();
16
+
inner();// Logs: "I'm from outer function"
17
+
18
+
// Task 2:Create a closure that maintains a private counter. Implement functions to increment and get the current value of the counter.
19
+
20
+
functioncreateCounter(){
21
+
letcounter=0;
22
+
23
+
return{
24
+
increment: function(){
25
+
counter++;
26
+
},
27
+
getValue: function(){
28
+
returncounter;
29
+
}
30
+
};
31
+
}
32
+
33
+
constcounter=createCounter();
34
+
counter.increment();
35
+
counter.increment();
36
+
console.log(counter.getValue());// Logs: 2
37
+
38
+
//Activity 2: Practical Closures
39
+
40
+
// Task 3:Write a function that generates unique IDs. Use a closure to keep track of the last generated ID and increment it with each call.
41
+
42
+
functioncreateIdGenerator(){
43
+
letlastId=0;
44
+
45
+
returnfunction(){
46
+
lastId++;
47
+
returnlastId;
48
+
};
49
+
}
50
+
51
+
constgenerateId=createIdGenerator();
52
+
console.log(generateId());// Logs: 1
53
+
console.log(generateId());// Logs: 2
54
+
55
+
//Task 4: Create a closure that captures a user’s name and returns a function that greets the user by name.
56
+
57
+
functioncreateGreeter(name){
58
+
returnfunction(){
59
+
console.log(`Hello, ${name}!`);
60
+
};
61
+
}
62
+
63
+
constgreetJohn=createGreeter("John");
64
+
greetJohn();// Logs: "Hello, John!"
65
+
66
+
67
+
// Activity 3: Closures in Loops
68
+
69
+
// Task 5:Write a loop that creates an array of functions. Each function should log its index when called. Use a closure to ensure each function logs the correct index.
70
+
71
+
functioncreateFunctions(){
72
+
letfunctions=[];
73
+
74
+
for(leti=0;i<5;i++){
75
+
functions.push(function(){
76
+
console.log(i);
77
+
});
78
+
}
79
+
80
+
returnfunctions;
81
+
}
82
+
83
+
constfunctions=createFunctions();
84
+
functions[0]();// Logs: 0
85
+
functions[1]();// Logs: 1
86
+
functions[2]();// Logs: 2
87
+
functions[3]();// Logs: 3
88
+
functions[4]();// Logs: 4
89
+
90
+
91
+
// Activity 4: Module Pattern
92
+
93
+
// Task 6:Use closures to create a simple module for managing a collection of items. Implement methods to add, remove, and list items.
0 commit comments