4

Even after using strict mode, I am able to update the object variable. How is possible? Is it possible to create constant objects at all?

"use strict";

const x = {a:"sss"}
x.a = "k"
console.log(x)

outputs:

{ a: 'k' }
Ulysses
  • 5,616
  • 7
  • 48
  • 84
  • 2
    From [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) _"The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned."_ – abhishekkannojia May 12 '17 at 06:38
  • @abhishekkannojia: Thanks for pointing out - I found the same but also found this easy fix online for the same (refer the answer). – Ulysses May 12 '17 at 06:39
  • @torazaburo: u are right but the way i started this question was different and i didn't know much about the behavior then so i didn't search by the title specified in the question. – Ulysses May 14 '17 at 09:55
  • Also, the question i asked is more specific to the behavior of the objects and properties specific scenario while the one you mentioned is a more generic question. Its kind of tough to call this as duplicate even if the question is a subset of it. Its hard to search for such questions if the problems cases differ. – Ulysses May 14 '17 at 10:04
  • Yes, it's hard to find duplicates some times. You'd probably have had better luck if your searches had included the word "variable", instead of "const object" as you used in your title--when you use `const`, you are applying that to a **variable**, not whatever object or value the variable happens to hold. I do think it is almost an exact dup, because it explicitly discusses the objects/properties issue you mention. –  May 14 '17 at 12:23

2 Answers2

5

Okay - so it is required to use Object.freeze call t make the object unchangeable. Even the strict mode isn't required.

const x = {a:"sss"}
Object.freeze(x);

x.a = "k"
console.log(x)

Outputs:

x.a = "k"
    ^

TypeError: Cannot assign to read only property 'a' of object '#<Object>'
Ulysses
  • 5,616
  • 7
  • 48
  • 84
5

ES6 const is not about immutability.

const only creates a read-only reference and that means that you cannot reassign another value for the object.

const creates an immutable binding and guarantees that no rebinding will happen.

Using an assignment operator on a const variable throws a TypeError exception:

Short example:

const x = {a:"sss"}
x={a:"k"}
console.log(x)

You will see the following message:

"Uncaught TypeError: Assignment to constant variable."

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128