Why const value is not changed but alter const object value?

In JavaScript, a constant declared using the const keyword cannot be reassigned, but the properties of the object assigned to a const variable can be altered. This is because const only prevents the reassignment of the variable, but it does not make the object itself immutable.

For example:

const obj = { name: 'John' };
obj.name = 'Jane';

console.log(obj.name); // 'Jane'

In this code, the obj constant is assigned an object with a property name set to 'John'. Although obj is declared as a constant using the const keyword, its property name can still be altered, and the value of obj.name can be changed from 'John' to 'Jane'.

To make an object immutable, you can use a library such as Object.freeze or use the Object.assign method to create a new object with the desired properties:

const original = { name: 'John' };
const immutable = Object.freeze(original);

immutable.name = 'Jane';

console.log(immutable.name); // 'John'

In this code, the original object is assigned to the immutable constant using the Object.freeze method, which makes the object immutable and prevents its properties from being altered. Attempting to change the value of immutable.name to 'Jane' will have no effect, and the value of immutable.name remains 'John'.

In summary, the reason why a constant value declared using the const keyword cannot be changed but the properties of a constant object can be altered is because const only prevents the reassignment of the variable, but it does not make the object itself immutable. To make an object immutable, you can use a library such as Object.freeze or use the Object.assign method to create a new object with the desired properties.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *