How are local variables referenced in closures? [duplicate]

You’re close…

Why does item have a value of ‘item3’? Doesn’t the for loop end when i becomes 3?

Yes.

If it ends shouldn’t item still be
‘item2’?

Nope. This example is a little tricky. During the last iteration of the loop, i is 2, but it references the 3rd element of the list array, which is 3. In other words, item == 'item' + list[2] == 'item3'

Or is the variable item created again when testList calls the functions?

No, you were almost right the first time. I think you just missed that item[2] has the value of 3.

Leave a Comment

tech