2

In JavaScript:

const a = 6;
a = 2; // Error

const o = {};
o = 7; // Error
o.a = 5; // Good. Why?

const o = {a:1};
o.a = 2; // Good. Why?

I found people sometimes define a const object but later change its value. Why a const can be changed after its definition?

AGamePlayer
  • 7,404
  • 19
  • 62
  • 119
  • changing a property of an object is not changing the object itself – Jaromanda X Dec 29 '19 at 03:51
  • 1
    You can't *reassign* a const-you can't change its reference. You can *the underlying thing it's referencing*, like adding object properties. You're looking to freeze the object – Andrew Li Dec 29 '19 at 03:52

4 Answers4

5

A variable declared with const means one thing: the standalone variable name cannot be reassigned with = later.

In contrast, o.a = 5; is not reassigning the variable name - it's mutating the content of the object, but it's not changing what the o variable points to in memory.

To prevent reassignment of a variable name, use const. To prevent mutation of an object is something entirely different - for that, you'd need something like Object.freeze or manipulate objects using immutable-js.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
4

In the first case, a is const and cannot be reassigned. In the second and third, the object o is const so that object cannot be assigned another value, but its properties are not const. See here: 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. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

Matt U
  • 4,970
  • 9
  • 28
1

const variables aren't enforced to be immutable.

From MDN:

Constants are block-scoped, much like variables defined using the let statement. The value of a constant can't be changed through reassignment, and it can't be redeclared.

Emphasis mine.

o.a = 5 isn't reassigning o; it's reassigning a property in o.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
1

For adding more information from the other answers, if you want to define a constant object property. You can try these ways:

const o = {
  get a() {
    return 1;
  }
};

o.a = 2;

// 1
console.log(o.a);

const o2 = {};

Object.defineProperty(o2, 'a', {
  value: 1,
  writable: false,
  enumerable: true,
  configurable: true
});

o2.a = 2;

// 1
console.log(o2.a);
Tân
  • 1
  • 15
  • 56
  • 102