Intro to JS question – JavaScript: Novice to Ninja, 2nd Edition – SitePoint Forums


from novice to ninja

If the variable refers to a non-primitive data type, such as an array, function, or object, using const won’t immutable . This means that the underlying data inside the object box change (called mutate the object).

please clarify

When you declare an object as ‘const’, you reserve memory for that const.
The assigned object is in a different memory location and the const is a reference to the object’s memory location
The system knows that it is an object and when you modify the object, you modify the object and not the const.
When you modify the object, it can either overwrite the existing object or create a new object and delete the existing object and modify the reference.
Think of const as a container for an object and you can modify what goes into the container but not the container.
It is the simple aprox. answer.

Constants cannot be reassigned.

const obj = { c: 2 }

const obj = { d: 3 }
// Uncaught SyntaxError: Identifier 'obj' has already been declared

obj = { d: 3 }
// Uncaught TypeError: Assignment to constant variable.

The contents of the reference types can however be modified. They are mutable.


// adding a property to the object
obj.d = 3
//  { c: 2, d: 3 }

// deleting a property from the object
delete (obj.c)
// { d: 3 }

Ditto for Arrays, another type of reference.


const arr = [1, 2, 3, 4]

arr = [6, 7, 8]
// Uncaught TypeError: Assignment to constant variable.

// add an item to the array
// [1, 2, 3, 4, 5]

// remove the last item
// [1, 2, 3, 4]

In short if a reference type is assigned to a constant you can always edit its contents. It is editable.


As it concerns the From novice to ninja lesson/book I moved it to the appropriate category :slight_smile:

1 like


Comments are closed.