liveBook · Manning

Immutable collection

As explained in Secrets of the JavaScript Ninja, Third Edition

An immutable collection is a collection whose contents cannot be modified after the collection is created.

An immutable collection cannot be changed after it is created. To add or remove an item, create a new collection with the change instead. This avoids unexpected mutations, especially when collections are passed to APIs. section 10.4

Objects, arrays, maps, and sets are mutable by default in JavaScript. TypeScript read-only types can make them effectively immutable. Creating copies has costs: it can use more CPU and memory, and shallow copies leave nested objects shared with the original. section 10.5 section 10.4.3

Updating read-only state with Immer

A read-only state can contain an array and a map. Immer’s produce callback receives a draft that can be changed; Immer uses those changes to return a modified copy, leaving the original state intact. section 10.4.3

Listing 10.15 Applying mutations to an immutable object with Immer
import { enableMapSet, produce } from "immer";
 
enableMapSet();  #A
 
interface NinjaMetadata {
  homeIsland: string;
}
 
type NinjaState = Readonly<{  #B
  ninjas: ReadonlyArray<string>;  #B
  ninjaMetadata: ReadonlyMap<string, NinjaMetadata>;  #B
  lastModified: number;  #B
}>;  #B
 
const initialState: NinjaState = {  #C
  ninjas: ["Kuma", "Hattori", "Yagyu"],  #C
  ninjaMetadata: new Map(  #C
    Object.entries({  #C
      Kuma: { homeIsland: "Honshu" },  #C
      Hattori: { homeIsland: "Hokkaido" },  #C
    }),  #C
  ),  #C
  lastModified: Date.now(),  #C
};  #C
 
const getStateWithNewNinja = (
  previousState: NinjaState,
  newNinja: string,
  newNinjaMetadata: NinjaMetadata,
): NinjaState => {
  return produce(previousState, (state) => {  #D
    state.ninjas.push(newNinja);  #D
    state.ninjaMetadata.set(newNinja, newNinjaMetadata);  #D
    state.lastModified = Date.now();  #D
  });  #D
};

const nextState = getStateWithNewNinja(  #E
  initialState,  #E
  "Yoshi",  #E
  { homeIsland: "Yoshi's Island" },  #E
);  #E

console.assert(
  nextState.ninjas.length ===
    initialState.ninjas.length + 1,
  "Added a new ninja",
);
console.assert(
  nextState.ninjaMetadata.size ===
    initialState.ninjaMetadata.size + 1,
  "Added metadata for the new ninja",
);

See a TypeScript example that declares read-only state and uses Immer to add a ninja and update its metadata. section 10.4.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Contrasts mutation with replacement, then shows TypeScript read-only types and Immer drafts for producing modified copies.
Examples
Uses read-only NinjaState with an array and map, then demonstrates changes through an Immer draft.
What you can do after
Apply it via Immer’s produce function to create a modified copy through draft mutations.
How it connects
Connects immutability to JavaScript objects, arrays, maps, sets, TypeScript read-only types, and Immer.

Also explained in

Compare how 30 books explain immutable collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.