乐闻世界logo
搜索文章和话题

What is the difference between mutable and immutable objects in JavaScript?

2024年6月24日 16:43

In JavaScript, objects can be categorized into mutable and immutable types.

Mutable objects are those that can have their content and structure modified after creation. In JavaScript, all object instances (e.g., Object, Array, and Function) are mutable. This means that after creating these objects, we can add new properties or methods, modify property values, or remove properties from the object.

For example, when we create an array, we can change it using various methods:

javascript
let myArray = [1, 2, 3]; // Create an array myArray.push(4); // Add a new element to the array myArray[0] = 10; // Change the value of the first element console.log(myArray); // Output: [10, 2, 3, 4]

In the above example, we create an array myArray, then add a new element using push, and then modify the first element's value. This demonstrates that arrays are mutable objects.

Immutable objects, conversely, are those whose content cannot be changed after creation. In JavaScript, primitive data types (such as Number, String, Boolean, Null, Undefined, Symbol, and BigInt) are immutable. This means that once these values are created, they cannot be changed; if you need a modified value, it actually creates a new value.

For example, the immutability of strings is shown as follows:

javascript
let myString = "Hello"; // Create a string myString[0] = "M"; // Attempt to change the first character of the string console.log(myString); // Output: "Hello"

In this example, although we attempt to change the first character of myString, the string remains "Hello". This shows that strings are immutable. If we want a different string, we need to create a new one:

javascript
let myString = "Hello"; let newString = "M" + myString.substring(1); // Create a new string console.log(newString); // Output: "Mello"

In the above example, newString is a new string created by combining a new character with a part of the original string, while the original myString remains unchanged.

This distinction is crucial for understanding how to manage data and references in JavaScript. Immutable objects provide value stability, while mutable objects offer flexibility. Understanding these concepts can help avoid common pitfalls, such as unintended side effects caused by directly modifying objects or arrays.

标签:JavaScript