logo
post image

Javascript Const Objects - Can They Be Changed ?

Using the const keyword on a Javascript object becomes a bit confusing — can the object's properties and methods be changed once defined ?

Yes, properties and methods be changed for a const object.

A const declaration does not mean that the value of the variable cannot be changed. It just means that the variable identifier cannot be reassigned.

const SomeOb = {
	id: 233,
	name: null,
};

// allowed
SomeOb.name = "John Doe";

// not allowed as variable cannot be reassigned
SomeOb = 10;

Primitive data types (Number, Boolean, String etc) are passed by value. The variable identifier holds the value, and since identifier cannot be changed for a const, it essentially means that the value cannot be changed here.

However complex data types such as objects and arrays are passed by reference. The variable identifier holds the reference, not the actual "value". So even if the object's properties and methods are altered, it does not change the actual reference.