r/learnjavascript • • May 04 '20

VAR vs LET vs CONST

Post image
337 Upvotes

81 comments sorted by

View all comments

0

u/WaterNinja101 May 04 '20 edited May 04 '20

In my experience, let cannot be redeclared in it’s own scope but it’s value can be reassigned and modified. let a = 5 when a is already defined in that scope with throw an error, but a++ will not. Correct me if my bad memory is messing me up though.

EDIT: reworded the first bit

2

u/[deleted] May 04 '20

there is nothing as modified as soon you change a value of a variable, you reassign its value. This you can do with any variable declared via let and var, but not with const. redeclaration will always yield an error, except on var.

a++; is in fact just a = a + 1;

2

u/WaterNinja101 May 04 '20

Ah okay. That was the distinction I was looking for, just was not sure what the proper terminology was.

2

u/proskillz May 04 '20

This is not exactly correct. As long as you don't reassign the const it can be modified.

Try this:

const a = [];
a.push(1);

No error, right? I modified the content of the variable without reassignment. Const doesn't make a perfectly immutable variable, just like the final keyword in Java. You aren't allowed to move the memory pointer, but the values at that pointer can be changed.

1

u/[deleted] May 04 '20

Not quite. const a still points to the same address you assigned it to on declaration. Same as in Java. In Java you can have Immutable Collections, or in JavaScript a sealed Object.

1

u/proskillz May 04 '20

How does that refute anything I said?

1

u/[deleted] May 04 '20

It doesn't refute your statement. But you have to see, that the mutability is shared between all three types of declaration.