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
// SOLUTION - 3 - Use different iterator variable i and j
75
+
76
+
for(vari=1;i<=3;i++){
77
+
setTimeout(function(){
78
+
console.log(`i: ${i}`)
79
+
},i*1000)
80
+
}
81
+
82
+
/* OUTPUT
83
+
84
+
i: 4
85
+
i: 4
86
+
i: 4
87
+
88
+
The reason the result gives 4,4,4 instead of 1,2,3 is because i is only one variable, and as we studied earlier, closure preserves access to variables (not value), so it preserves the value of the last instance of i.e. 4.
89
+
90
+
To receive 3 different values, we needed 3 different variables, which can be achieved by using a block scoped declaration */
91
+
92
+
for(vari=1;i<=3;i++){
93
+
letj=i
94
+
setTimeout(function(){
95
+
console.log(`j: ${j}`)
96
+
},j*1000)
97
+
}
98
+
99
+
/* OUTPUT -
100
+
j: 1
101
+
j: 2
102
+
j: 3
103
+
It preserves separate values of j in each iteration. j runs every time as the loop iterates New j is created in every iteration */
0 commit comments