Advertisement
Beginner JavaScript, Functional Programming

What does 'immutability' mean and why does functional code favor it?

Short answer

Immutability means not modifying data after it's created — instead, you produce new data structures with the desired changes. This avoids bugs from shared mutable state and makes it easier to track how and when data changes.

Save JavaScript mock interview
Advertisement
AModel answer
Immutability means not modifying data after it's created — instead, you produce new data structures with the desired changes. This avoids bugs from shared mutable state and makes it easier to track how and when data changes.
// Mutating (avoid)
const arr = [1,2,3];
arr.push(4);

// Immutable (preferred)
const arr2 = [...arr, 4];
Real-world example
Avoiding accidental shared-state bugs in React, where mutating state directly can cause missed re-renders.
Likely follow-ups
  • Does immutability have a performance cost, and how is it usually managed?
Related topics