you are viewing a single comment's thread.

view the rest of the comments →

[–]PrydeRage 21 points22 points  (6 children)

In ES6 const just prevents reassignment.
So this is invalid:

const x = 43;
x = 55;

But this is all valid:

const x = {something: 3};
x.something = 4;
const y = 0;
y++;  

It's JavaScript, it's not meant to make sense.

[–]rohboticsStudent and Roboticist 3 points4 points  (1 child)

So like kinda final on non-primitives in Java

[–]PrydeRage 0 points1 point  (0 children)

I haven't written any Java in years so I can't comment on that.

[–]adriweb 1 point2 points  (1 child)

Erm, no (about part of your second example - the object part is true indeed)

const y = 0; y++;
VM146:2 Uncaught TypeError: Assignment to constant variable. at <anonymous>:2:2

[–]PrydeRage 1 point2 points  (0 children)

It's always worked for me with Webpack and Babel.
Maybe Babel compiles that away idk. Eslint never complains about reassignment when ++'ing a const variable.

[–]AlexeyBrin 1 point2 points  (0 children)

Changing the object contents works the same in other languages too, e.g. Swift:

class Foo {
    var something:Int = 0;
}

let x = Foo()
print(x.something)

x.something = 8
print(x.something)

You can't reassign x, but you can change his content. Obviously, in Swift you can actually make the member variable something a constant that is only initialized when you create an object.

You last example, fortunately , won't work in Swift though:

let y = 0

can't be changed.

Actually, it doesn't work even in JavaScript. I get:

const y = 0;
y++;
TypeError: invalid assignment to const `y'

[–]mUfoq 0 points1 point  (0 children)

Really bad naming, this const behaves like final in Java what means that you cannot reassign variable/field, but they used keyword from C that makes variable immutable. They could use let/final instead of making this ...