23 Feb 2024




Beginner

In JavaScript, the concepts of mutable and immutable refer to whether an object's state can be changed after it is created.

  1. Mutable:

    • Objects that are mutable can be modified or changed after their creation.
    • Examples of mutable objects in JavaScript include arrays and objects.
    • When you modify a mutable object, it affects the original object directly.
    let mutableArray = [1, 2, 3];
    mutableArray.push(4); // Modifies the original array
    
  2. Immutable:

    • Objects that are immutable cannot be changed once they are created.
    • Strings and numbers in JavaScript are examples of immutable objects.
    • When you perform an operation that appears to modify an immutable object, it actually creates a new object with the modified value.
    let immutableString = "Hello";
    let newString = immutableString + ", World!"; // Creates a new string, doesn't modify the original
    
    let immutableNumber = 5;
    let newNumber = immutableNumber * 2; // Creates a new number, doesn't modify the original
    

Immutable objects have some advantages, such as making it easier to reason about the state of your application, avoiding unintended side effects, and simplifying concurrency control. However, there can be performance implications as creating new objects instead of modifying existing ones may involve more memory allocation.

In modern JavaScript, there are also libraries and techniques (like using the const keyword, or using immutable data structures provided by libraries like Immutable.js) that facilitate working with immutable data structures.

javascript
mutable
immutable
objects