Why can't I use let to reassign a variable?

Why can’t I reassign the value?
It worked when I use var instead of let.
Why?

The syntax rules for let are more strict than with var, for one, and for good reason… Why declare a variable more than once? let declares a variable in its current block scope. After that, we can change the value as often as we need.

let sale = true;
sale = false;

let does work like var in terms of declaring variables without defining them.

let a;
var b;

Because loops like for and while consist of their own block of code, let is encouraged to keep the loop data from leaking out. This is useful, and the reason it was incorporated in ES. var is pretty much on the way out as kind of the lame duck in the pond. You’ll still see it a lot, but less and less as the years pass.

Final note, a variable inside a block that is defined by assignment alone becomes a global, automatically.

for (i of [1,2,3,4]) {
    console.log(i);
}
console.log(i);

1
2
3
4
4

We probably don’t want this happening in our program for perhaps less than obvious reasons, but make it a rule to always use a keyword to declare variables. They will be adopted into the scope in which they are declared.

11 Likes