Comments by "D K" (@DK-ox7ze) on "Closures Explained in 100 Seconds // Tricky JavaScript Interview Prep" video.
-
Seems like closures store values by reference if it's an object or array. The following code prints 3, 3, 3 :
for(let j = {a: 0}; j.a < 3; j.a++) {
setTimeout(() => console.log(j.a), 100);
}
However, the following code prints 0, 1, 1. That's wierd because both increment() and view() have closure over inner variable. Since inner is a simple variable, the closures should contain its copy. But here we see that when we call view() again, it prints 1, and not 0. Which means it's referencing the same copy:
function outer() {
let inner = 0;
return {
increment: () => {
inner++;
console.log(inner);
},
view: () => console.log(inner)
}
}
const closure = outer();
closure.view();
closure.increment();
closure.view();
1
-
1