Preparation
πŸ’‘ ⏐ JavaScript Questions
9. Mutable/Immutable data types

Mutable vs. Immutable Data Types

In JavaScript, data types can be categorized as either mutable or immutable, depending on whether their values can be changed after they are created. Understanding the difference between these two types is crucial for writing efficient and reliable code.

Mutable Data Types:

Mutable data types are those whose values can be modified after creation. In JavaScript, the main mutable data types are objects and arrays.

  • Objects: Objects in JavaScript are mutable. This means that their properties can be added, modified, or removed after the object is created. For example:

    let person = { name: "Alice", age: 30 };
    person.age = 31; // Mutable change
  • Arrays: Arrays are also mutable. You can change the elements of an array, add new elements, or remove existing ones. For example:

    let numbers = [1, 2, 3, 4];
    numbers.push(5); // Mutable change, adding an element
    numbers[0] = 0; // Mutable change, modifying an element

Immutable Data Types:

Immutable data types are those whose values cannot be changed after creation. In JavaScript, primitive types and frozen objects fall into this category.

  • Primitive Types: Primitive data types such as numbers, strings, and booleans are immutable. Once they are created, their value cannot be changed. For example:

    let x = 5;
    x = 10; // This assigns a new value to x, but it doesn't change the original value of 5
  • Frozen Objects: You can make an object immutable by freezing it using Object.freeze(). Once an object is frozen, its properties cannot be added, removed, or modified. For example:

    let obj = { name: "Bob", age: 25 };
    Object.freeze(obj);
    obj.age = 26; // This change will not take effect

Understanding the distinction between mutable and immutable data types is essential for writing robust and bug-free JavaScript code. Immutable data types promote safer and more predictable code, particularly in scenarios where state management is complex or critical. They help prevent unintended changes and side effects, leading to more maintainable and reliable software.