Javascript var vs let declaration question 1

Introduction

What is the output of the following code:

for (var i = 0; i < 5; ++i) { 
    setTimeout(() => console.log(i), 0) 
} 

for (let i = 0; i < 5; ++i) { 
    setTimeout(() => console.log(i), 0) 
} 

Note

The loop exits with its iterator variable still set to the value.

This caused the loop to exit: 5.

When the timeouts later execute, they reference this same variable, and consequently console.log its final value.

When using let to declare the loop iterator, JavaScript engine will declare a new iterator variable each loop iteration.

Each setTimeout references that separate instance.

for (var i = 0; i < 5; ++i) { 
    setTimeout(() => console.log(i), 0) 
} 

for (let i = 0; i < 5; ++i) { 
    setTimeout(() => console.log(i), 0) 
} 



PreviousNext

Related