Search code examples
javascriptvarlet

Is let the same used inside and outside a loop


The question pop up in my head when I read example 6 in this post https://stackoverflow.com/a/111111/6359753

Will there ever be a difference between

// Example 1
let i;
var arr = [1,2,3]
for (i=0; i<arr.length; i++){
 // do stuff
}

and

// Example 2
var arr = [1,2,3]
for (let i=0; i<arr.length; i++){
 // do stuff
}

If they are the same, why are they the same?

In other words, I don't really understand let's scope. If declared outside the loop, are they scoped outside the loop? example 2's let clearly are scoped inside the for loop, but example 1 I'm not so sure.


Solution

  • If it is declared in the for loop, it is visible only in the loop's body. Outside of loop i is not visible.

    var arr = [1,2,3];
    
    for (let i=0; i<arr.length; i++) {
     
    }
    
    console.log(i);

    If it is declared outside the for loop, the scope of the variable is the closest surrounded block {}.

    let i;
    var arr = [1,2,3];
    
    for (i = 0; i < arr.length; i++) {
    
    }
    
    console.log(i);