Skip to main content
Practice Problems

What is immutability?

Understanding Immutability

Definition of Immutability

Immutability refers to the concept where an object cannot be modified after it has been created. Instead of altering the original object, a new object is created with the desired changes.

Example of Immutability in JavaScript

To illustrate immutability, consider the following code snippet:

javascript
// A better approach is to use .map to create a new array with the updated values const gadgets = [ { name: "Tablet", cost: 300 }, { name: "Smartwatch", cost: 250 } ]; const revisedGadgets = gadgets.map((gadget) => { return { ...gadget, cost: gadget.cost + 50, // creates a new object instead of modifying the existing one }; });

Benefits of Immutability

This technique is widely adopted in the JavaScript world, especially on the frontend side, for example in most libraries and frameworks.

Emerging Immutable Alternatives in JavaScript

Additionally, immutable alternatives to methods are emerging in JavaScript itself. Some of these methods include:

  • toSorted
  • toReversed
  • with
  • toSpliced

These methods provide developers with more tools to work with immutable data structures effectively.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems