0

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)?

3
  • github.com/getify/You-Dont-Know-JS Commented May 16, 2018 at 7:55
  • @t3__rry this is a great resource, thanks Commented May 16, 2018 at 10:18
  • Glad it helped you @DavidR Commented May 16, 2018 at 13:47

1 Answer 1

0

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 ...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.