FP #5 — Immutability Patterns

Object.freeze, deep freeze, structuredClone, spread-based updates, Immer-style produce(), and Immutable.js concepts — preventing unintended mutation.

10 min read
JavaScript
Functional
Immutability

TABLE OF CONTENTS
FP #5 — Immutability Patterns

Immutability means never modifying data in place — always creating new copies with changes applied. It prevents accidental mutations, enables reliable change detection, and is foundational to React, Redux, and functional programming. This article covers every immutability pattern in JavaScript.

Prerequisites: Data #1 — Deep Clone


1. Preventing Mutation — const vs Object.freeze

const prevents reassignment. It does NOT prevent mutation:

Loading editor...

Object.freeze() makes an object shallowly immutable:

Loading editor...


2. Deep Freeze — Recursive Immutability

Loading editor...


3. Immutable Updates — Spread, Map, Filter

The standard pattern: return a new copy with changes applied:

Loading editor...


4. structuredClone() — Deep Copy Built Into the Platform

Loading editor...


5. Immer-Style produce() — Write Mutable, Get Immutable

Immer lets you write "mutating" code that actually produces an immutable copy:

Loading editor...


6. Immutability Library Comparison

Loading editor...


Key Takeaways

  • const prevents reassignment, NOT mutation. Object.freeze is shallow.
  • Use spread/map/filter for immutable updates — the standard React/Redux pattern.
  • structuredClone() is the modern deep copy — prefer it over manual implementations.
  • Immer-style produce() lets you write "mutating" drafts that produce immutable results.
  • In production, don't deepFreeze large objects — it has a performance cost. Use it in development for debugging.

Next: Web APIs #1 — requestAnimationFrame & requestIdleCallback — sync JS to the display refresh and run low-priority work.


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI