JavaScript Immutability

Beginner
6 min read
Updated: Nov 2026
3 examples

Definition and Usage

Immutability means you treat values as read-only: instead of changing an array or object in place, you create a new one with the update applied.

JavaScript Syntax

JavaScript
const list = [1, 2, 3];
const next = [...list, 4];

console.log(list.join(", "));
console.log(next.join(", "));
Try it Editor

How It Works

  1. Original stays. list is unchanged.
  2. New copy. Spread builds a fresh array and appends 4.
  3. Safer pipelines. Callers can keep referring to the old value without surprises.

Examples

Example 1 — Update an Object Field

Copy an object and override one key.

JavaScript
const user = { name: "Ada", role: "dev" };
const promoted = { ...user, role: "lead" };
console.log(user.role);
console.log(promoted.role);
Try it Editor

How It Works

  1. Spread copy. Own enumerable fields are copied.
  2. Override. role is replaced only on the new object.

Example 2 — Mutation Side Effect

See how in-place push surprises shared references.

JavaScript
const a = [1, 2];
const b = a;
b.push(3);
console.log(a.join(", "));
Try it Editor

How It Works

  1. Same reference. b points at the same array as a.
  2. push mutates. Both variables see the new length.

Example 3 — Ramda Style

Ramda helpers return new structures instead of mutating.

JavaScript
// Conceptual twin of R.append(4, list)
const list = [1, 2, 3];
const appended = list.concat(4);
console.log(list.length, appended.length);
Try it Editor

How It Works

  1. concat copies. A new array is returned.
  2. Source intact. Original length remains 3.

Frequently Asked Questions

Updating data by producing new values instead of changing existing ones in place.

No. Arrays and objects are mutable by default. You choose immutable patterns (spread, concat, libraries like Ramda).

Predictable state, safer sharing, and easier undo/time-travel debugging.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful