1

I have been working on some exercise with let and const and found something interesting with const along with objects assignments.

As per definition: In JavaScript, const means that the identifier can’t be reassigned.

const numConst = 20;
numConst = 40;
console.log("numConst", numConst);
Uncaught TypeError: Assignment to constant variable.

Whereas when I try to modify the object declared with const, it is allowed:

const person = { name: "test", age: 20 };
person.age = 40;
console.log("person.age", person.age); // outputs: person.age 40

Why does const behave differently with object?

zeeshanseikh
  • 117
  • 7
Shankar Ganesh Jayaraman
  • 1,401
  • 1
  • 16
  • 22
  • 1
    Objects are reference type, you can not re-assign person with a new value/object but you are free modify contents of the object.. Same with other variants of objects a common use-case are Arrays, you can add/remove items from a array but you may not be able to re-assign a new array to a variable if you defined it with const. – Shub Mar 04 '21 at 13:18
  • 2
    also If you want to prevent modification of values within an object, [Object.freeze()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) might be helpful. – Shub Mar 04 '21 at 13:20
  • 1
    https://stackoverflow.com/questions/44604212/when-to-use-const-with-objects-in-javascript#:~:text=The%20const%20keyword%20makes%20a,object%20to%20a%20const%20variable. –  Mar 04 '21 at 13:33
  • 1
    `const` behaves *exactly* the same with objects. You cannot reassign the identifier `const obj = {foo: 1}; obj = {bar: 2}` is an error. – VLAZ Mar 04 '21 at 13:33

3 Answers3

2

https://www.w3schools.com/JS/js_const.asp

The keyword const is a little misleading.

It does NOT define a constant value. It defines a constant reference to a value.

Because of this, we cannot change constant primitive values, but we can change the properties of constant objects.

const a = {foo: 'bar'}; defines a new object (thus a new reference). this reference will be stored in a.

when invoking a = {bar: 'foo'} later, you tell the program, to change the reference a. This is not allowed due to the const constraint.

On the other hand, a.bar = 'foo' will modify the value refenreced by a, but not the reference itself.

Hollyol
  • 827
  • 1
  • 13
  • 25
  • W3Schools is a little misleading. `const` DOES define a constant value. "reference to a value" is basically a meaningless thing they mentioned for reasons unknown. 1. The value of an object *is its reference*. So `x = {}` is not "reference to a value". This is *why* `x === {}` would fail - the value comparison fails because the two values are different references. It's also why `x === x` succeeds because the two values are equal - it's the same reference. 2. What W3Schools seem to mean by "reference to a value" is what we call "identifier" or "binding". You know a "variable". – VLAZ Mar 04 '21 at 14:27
  • 1
    They introduced confusing terminology by re-using other terms in order to avoid the correct and unambiguous term. Finally, "constant primitive values" is also meaningless. Primitives are already immutable. You cannot "change" `4` or `"hello"`, etc. You change *the identifier* they would be assigned to - `n++` or `s += "world"`. – VLAZ Mar 04 '21 at 14:27
  • @VLAZ, thanks for the insights, i will look further on it later and edit my answer accordingly, unless you'd like to edit this answer or submit your own – Hollyol Mar 04 '21 at 14:44
0

const behave differently for object because when you create something like:

const person = {name:"test",age:20};

here person holds the reference (memory address) in it and when you change some data in object its reference is not changed but the key:value pair is changed that's the reason it doesn't show error in case of objects.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
0

You assign an object to const which is reference type. Now if you add new keys to object or modifiy the existing values of key you can do so because person preserving the reference of that object and by using person.age you are changing the value of object not the reference. But if you try to assign a new reference to person like this

  const person = { name: 'test', age: 20 };
  person = { name: 'hi', age: 10 };
  console.log(person);

you will get error Uncaught TypeError: Assignment to constant variable.

Both arrays and objects are reference type and by using same reference you can add or remove keys from object or can change values. Same as using arrays you can push new values or can pop but can't assign a new reference to that const.