Home > Web Front-end > JS Tutorial > How Can JavaScript Constants Be Modified If They\'re Immutable?

How Can JavaScript Constants Be Modified If They\'re Immutable?

Susan Sarandon
Release: 2024-11-30 01:04:12
Original
432 people have browsed it

How Can JavaScript Constants Be Modified If They're Immutable?

Misconception of Constant Object in JavaScript

Despite referring to ES6 specifications that emphasize the immutability of constants, JavaScript allows seemingly contradicting actions on constant objects. When assigning a different value to a constant object, it remains unchanged, yet adding or removing elements within the object is seemingly possible.

Understanding Constant Semantics

According to the MDN documentation, "constant cannot change through re-assignment" and "constant cannot be re-declared." Crucially, this implies that the reference to the object is constant, not the object itself. You cannot assign a new object to the constant variable, but you can modify the contents of the object.

Example: Modifying an Array

Consider the following code snippet:

const myArray = [];
myArray.push(1);
console.log(myArray); // Output: [1]
Copy after login

In this case, the reference to the myArray array remains unchanged as it is still pointing to the same array object. However, the push() operation adds an element to the array, altering its contents but not violating the constant semantics.

Example: Adding Properties to an Object

Similarly, you can add properties to a constant object without modifying the reference:

const myObject = {};
myObject.foo = 'bar';
console.log(myObject); // Output: {foo: "bar"}
Copy after login

Expectations vs Reality

It's important to distinguish between re-assignment and modification. While re-assignment creates a new reference, modification operates on the same object reference. In the case of constant objects, re-assignment is prohibited to ensure immutability, while modification of the object's contents is still allowed.

The above is the detailed content of How Can JavaScript Constants Be Modified If They\'re Immutable?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template