JavaScript Interview Question #179

What is immutability, and why is it useful?

Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced

Quick Interview Answer

Immutability means treating existing values or data structures as unchanged and producing new values for updates. Primitive JavaScript values are immutable, while objects and arrays are mutable by default.

Detailed Explanation

Immutability means treating existing values or data structures as unchanged and producing new values for updates. Primitive JavaScript values are immutable, while objects and arrays are mutable by default.

Immutable update patterns can make state transitions easier to understand, support predictable change detection, and reduce accidental shared-state bugs. However, copying large structures unnecessarily can have a cost, so immutability should be applied with appropriate data structures and architecture.

Code Example

const user = {
    id: 1,
    name: "Asif",
    active: true
};

const updatedUser = {
    ...user,
    active: false
};

console.log(user.active);        // true
console.log(updatedUser.active); // false