12

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.

1
  • 1
    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. Commented Sep 5, 2018 at 16:57

2 Answers 2

18

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

Comments

7

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.

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.