Mutable & Immutable

In programming, data types can be classified as mutable or immutable based on whether their values can be changed after they are created. In JavaScript, there are several data types, and each of them can be classified as either mutable or immutable.

Mutable data types are those whose values can be changed after they are created. This means that we can modify the original value of the data type without creating a new one. Examples of mutable data types in JavaScript include objects, arrays, and maps. For instance, if we have an object in JavaScript, we can add, delete or modify its properties after it is created.

Here's an example of a mutable object in JavaScript:

let person = { name: "John", age: 30 };
person.age = 31; // Modifying the age property
console.log(person); // Output: { name: "John", age: 31 }

On the other hand, immutable data types are those whose values cannot be changed after they are created. If we want to modify the value of an immutable data type, we must create a new one. Examples of immutable data types in JavaScript include strings, numbers, and booleans. For instance, if we have a string in JavaScript, we cannot modify its original value.

Here's an example of an immutable string in JavaScript:

let name = "John";
name += " Doe"; // Creating a new string value
console.log(name); // Output: "John Doe"

It's important to note that even though some data types like arrays and objects are mutable, their references can be immutable. This means that we can change their properties or values, but we cannot change their identity or memory location. For instance, if we have an array in JavaScript, we can modify its elements, but we cannot change its memory location.

Here's an example of a mutable array reference in JavaScript:

let arr1 = [1, 2, 3];
let arr2 = arr1; // Creating a reference to the original array
arr2.push(4); // Modifying the original array through the reference
console.log(arr1); // Output: [1, 2, 3, 4]
console.log(arr2); // Output: [1, 2, 3, 4]

In this example, arr1 and arr2 are two different references to the same mutable array. When we modify the array through one of the references, the changes are reflected in both references.

In summary, mutable data types can be modified after they are created, while immutable data types cannot. It's important to understand the mutability of data types to write efficient and correct code.

Last updated