Immutability in JavaScript

Learn how to write predictable, bug-free code by embracing immutable data patterns.

Why Immutability Matters

Immutability is a core concept in functional programming that brings numerous benefits to your JavaScript applications.

Predictability
Data doesn't change unexpectedly
Debugging
Track changes through time
Performance
Enable memoization & optimization
Concurrency
Safe parallel processing

🔄 Mutability vs Immutability

Understand the fundamental difference between mutable and immutable approaches.

JavaScript Editor
Key Differences:
AspectMutableImmutable
Data ChangesModify originalCreate new copy
Side EffectsCommonAvoided
Reference EqualitySame referenceNew reference
Thread SafetyNot safeSafe

🎯 Primitive vs Reference Types

JavaScript has different rules for different data types.

JavaScript Editor
Copying Techniques:
Shallow Copy:
  • {...obj} - Spread operator
  • Object.assign(, obj)
  • array.slice()
  • [...array]
  • Array.from(array)
Deep Copy:
  • JSON.parse(JSON.stringify(obj))
  • structuredClone(obj) (modern)
  • Lodash _.cloneDeep()
  • Custom recursive function

🔧 Immutable Operations

Learn how to perform common operations immutably.

JavaScript Editor
Array Operations:
// Add
            [...arr, item]           // push
            [item, ...arr]           // unshift

            // Remove
            arr.slice(1)             // shift
            arr.slice(0, -1)         // pop
            arr.filter(x => x !== value)

            // Update
            arr.map(x => x === old ? new : x)

            // Insert
            [...arr.slice(0, i), item, ...arr.slice(i)]
Object Operations:
// Add/Update
            {...obj, key: value}

            // Remove
            const {key, ...rest} = obj

            // Multiple updates
            {...obj, ...updates}

            // Nested update
            {
            ...obj,
            nested: {
                ...obj.nested,
                key: value
            }
            }

🏗️ Deep Immutability & Structural Sharing

Advanced patterns for efficient immutable updates.

JavaScript Editor
Structural Sharing Benefits:
  • Memory efficient: Unchanged parts share references
  • Fast equality checks: Compare references instead of deep equality
  • Predictable updates: Only changed parts get new references
  • Memoization friendly: Cache computations based on reference equality

🚀 Real-world Example: Redux State Management

JavaScript Editor
Redux Principles:
  1. Single source of truth: Entire app state in one store
  2. State is read-only: Only changed through actions
  3. Changes via pure functions: Reducers produce new state
  4. Immutable updates: Never mutate existing state

⚡ Performance Patterns

JavaScript Editor
When to Use Immutability:
  • ✅ State management libraries
  • ✅ Configuration objects
  • ✅ Concurrent operations
  • ✅ Data transformation pipelines
  • ✅ Functional programming
When to Be Cautious:
  • ❌ High-frequency updates (games)
  • ❌ Memory-constrained environments
  • ❌ Large object deep clones
  • ❌ Performance-critical loops
  • ⚡ Simple local variables

🛠️ Immutability Tools & Libraries

Immer

Create immutable state by mutating a draft. Best for Redux reducers and complex updates.

npm install immer
Immutable.js

Persistent immutable data structures. Great for large datasets with frequent updates.

npm install immutable
Redux Toolkit

Built-in immutable update patterns with Immer. Standard for modern Redux.

npm install @reduxjs/toolkit
Native JavaScript Methods:
  • Object.freeze() - Shallow immutability
  • Object.seal() - Prevent adding/removing
  • Object.preventExtensions() - Prevent adding
  • structuredClone() - Native deep clone
  • Spread operator (...)
  • Array.prototype methods

Mastered Immutability?

You've learned how to write predictable, maintainable code with immutable patterns. These concepts are essential for modern JavaScript development.