Search code examples
javascriptscopevarlet

What is a real-world example of block scope being useful in JavaScript?


let and const have introduced block-level scoping to JavaScript, and I now understand the difference. But I'm yet to find a compelling real-world example where let has an advantage over var.

What does block-scoping offer in practical terms (illustrated by example)?


Solution

  • 1) It creates consistency with other languages:

    With var it is often quite unclear where a variable is defined and where we can access it and were not:

     if(false) {
        var a = 1;
     } else {
        a = 2; // wtf
     }
     alert(a);
    

    With let its obvious:

    let a;
    if(false) { a = 1; } else { a = 2; }
    

    2) It allows useful closuring in for loops:

     for(var i = 0, i < 10; i++)
       setTimeout(() => console.log(i), 100);
       // 10 10 10 10 ...
    
     for(let i = 0, i < 10; i++)
       setTimeout(() => console.log(i), 100);
       // 0 1 2 3 4 5 6 ...