Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why object const can be changed after definition in JavaScript? [duplicate]

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?

like image 757
AGamePlayer Avatar asked Sep 06 '25 03:09

AGamePlayer


2 Answers

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.

like image 102
Matt U Avatar answered Sep 07 '25 23:09

Matt U


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.

like image 30
CertainPerformance Avatar answered Sep 07 '25 22:09

CertainPerformance