10

Using JavaScript ES6, I am surprised that doing:

const a = {};
a.foo = 'bar';
a.foo = 'car';

Is valid. Why is this? I would have assumed const would mean you cannot change the a empty object and apply new properties. Even further, I would also have assumed you cannot change the value of a property of a once it is set.

Justin
  • 38,686
  • 72
  • 185
  • 276
  • I would say that one 'good' thing I do like about Java is that its constant variables are a lot clearer to beginners. Java uses `final` (which might correctly imply that this is the final value the variable will hold) instead of `const` (which might falsely imply that the value of this variable are constant and cannot be changed). Write `const`, but imagine it says `final` instead when declaring constant javascript variables. – Jack G Sep 05 '18 at 16:57

2 Answers2

17

Only the variable assignment is constant. Any objects or arrays referenced stay mutable.

const a = {one: 1};
a.three = 3; // this is ok.
a = {two: 2}; // this doesn't work.

What you can do is use Object.freeze:

const a = {one: 1};
Object.freeze(a);
a.three = 3; // silently fails.
// a is still {one: 1} here.
Blixt
  • 48,513
  • 13
  • 117
  • 151
6

No, const a means you cannot change the value of the variable a. Its value is always the same object; changing properties of an object doesn't make it into a different object.

Using an analogy, I am the same Person whether amadan.jacket = null or amadan.jacket = "Heavy Winter Jacket". amadan is constant.

To make the properties immutable, you would either have to make the properties explicitly readonly by writable: false, or use Object.freeze or Object.seal (differences) to make the entire object immutable.

Community
  • 1
  • 1
Amadan
  • 179,482
  • 20
  • 216
  • 275