DEV Community

Discussion on: How you can learn Closures in JavaScript and understand when to use them

Collapse
 
quozzo profile image
Quozzo

You don't need an IIFE if you declare a variable within the loop using let, because unlike its var counterpart, let is scoped to a code block and not the function.

Collapse
 
softchris profile image
Chris Noring

good point will add that :)

Collapse
 
z2lai profile image
z2lai

I think along with explaining why the wrong answer to the interview questions is due to setTimeout being asynchronous, you should also include that var doesn't obey block scope AND it behaves like the following when the same variable is declared multiple times within the same scope such as when declared in a for loop:

for (var i = 0; i < n; i++) {
    // ...
}

becomes

var i;    // declared here
for (i = 0; i < n; i++) {    // initialized here
    // ...
}

So the 10 console logs would be referring to the same "globally" scoped variable after it's been incremented to 10.