Search code examples
javascriptfor-loopvarlet

JavaScript - What is the difference between declaring a iteration variable using a let versus a var keyword inside a for-loop?


What is the difference between using a let in the body of the for loop and a var specifically in the body of a JavaScript for loop? Do they work differently and why?

Example:

Using let

for (let i = 0; i < 10; i++) {

}

Using var

for (var i = 0; i < 10; i++) {

}

Do these work the same way or differently behind the scenes, does one actually functions better?

Does this difference apply to a while loop and a do-while loop too?


Solution

  • let is block scoped and var is not. With let, you cannot use i outside the forloop body. With var (function scoped or globally scoped) you can.

    for (var j = 0; j < 10; j++) {
    
    }
    
    console.log(j);
    
    
    for (let i = 0; i < 10; i++) {
    
    }
    
    console.log(i);

    You can run the for loop with var in your chrome console, and will see that i has been attached to the window object.