Modifying constants

suggest change

Declaring a variable const only prevents its value from being replaced by a new value. const does not put any restrictions on the internal state of an object. The following example shows that a value of a property of a const object can be changed, and even new properties can be added, because the object that is assigned to person is modified, but not replaced.

const person = { 
    name: "John" 
};
console.log('The name of the person is', person.name);

person.name = "Steve";
console.log('The name of the person is', person.name);

person.surname = "Fox";
console.log('The name of the person is', person.name, 'and the surname is', person.surname);

Result:

The name of the person is John
The name of the person is Steve
The name of the person is Steve and the surname is Fox

person is a constant binding. person = {} throws TypeError. The example changes properties of the same object. It does not replace the object.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents