Skip to content
jshacks.dev
Patterns

The Memento Pattern in JavaScript, With Real Examples

The memento pattern saves an object's state so you can restore it later without exposing its internals. See undo, drafts and snapshots in JavaScript.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js and Vite logos.

The memento pattern captures an object's internal state in a separate object, the memento, so the state can be restored later, without breaking the object's encapsulation. The object that owns the state, the originator, creates mementos and consumes them. A third party, the caretaker, stores them and hands them back without ever looking inside. The classic uses are undo, "revert to saved", checkpoints in a long computation and form drafts. This post builds it in JavaScript on Node.js 24: a text editor with snapshots, a version with private fields so only the originator can read a memento, a bounded history with undo and redo, and a comparison with structuredClone and with the command pattern, which also supports undo but works differently. Every sample prints its output.

The problem: restoring private state

Suppose an object keeps its state private, as it should. An outside caller who wants to snapshot it has two bad choices.

problem.mjsJavaScript
class Editor {
  #text = "";
  #cursor = 0;

  type(chars) {
    this.#text = this.#text.slice(0, this.#cursor) + chars + this.#text.slice(this.#cursor);
    this.#cursor += chars.length;
  }

  get content() {
    return this.#text;
  }
}

const editor = new Editor();
editor.type("Hello");
const saved = editor.content;
editor.type(", world");
console.log(editor.content, "|", saved);
Text
Hello, world | Hello

The caller saved the text but has no way to put it back, because the setter does not exist, and the cursor is invisible so it cannot be saved at all. Exposing #text and #cursor to let outsiders snapshot them would break the encapsulation that kept the class safe. The memento lets the originator package its own state.

The originator, the memento and the caretaker

memento.mjsJavaScript
class Editor {
  #text = "";
  #cursor = 0;

  type(chars) {
    this.#text = this.#text.slice(0, this.#cursor) + chars + this.#text.slice(this.#cursor);
    this.#cursor += chars.length;
  }

  moveCursor(position) {
    this.#cursor = Math.max(0, Math.min(position, this.#text.length));
  }

  get content() {
    return `${this.#text.slice(0, this.#cursor)}|${this.#text.slice(this.#cursor)}`;
  }

  save() {
    return new EditorMemento(this.#text, this.#cursor);
  }

  restore(memento) {
    const { text, cursor } = memento.state(this);
    this.#text = text;
    this.#cursor = cursor;
  }
}

class EditorMemento {
  #text;
  #cursor;
  #owner;

  constructor(text, cursor) {
    this.#text = text;
    this.#cursor = cursor;
    Object.freeze(this);
  }

  state() {
    return { text: this.#text, cursor: this.#cursor };
  }
}

const editor = new Editor();
editor.type("Hello");
const checkpoint = editor.save();
editor.type(", world");
editor.moveCursor(0);
editor.type(">> ");
console.log(editor.content);

editor.restore(checkpoint);
console.log(editor.content);
Text
>> |Hello, world
Hello|

The checkpoint remembered both the text and the cursor position. After more typing and a cursor move, restore put everything back: Hello with the cursor at the end, drawn here as Hello|. The memento is frozen, so nobody can edit a saved snapshot. In real JavaScript there is no way to make state() callable only by the originator, since the language has no friend classes, so the guarantee is a convention. If you want stricter protection, keep the mementos in a WeakMap inside the module and hand out opaque tokens.

An opaque memento with a WeakMap

The caretaker can hold a token that reveals nothing, while the real data is stored where only the originator can reach it.

opaque.mjsJavaScript
const snapshots = new WeakMap();

class Counter {
  #value = 0;
  increment() {
    this.#value += 1;
  }
  get value() {
    return this.#value;
  }
  save() {
    const token = Object.freeze({});
    snapshots.set(token, { value: this.#value });
    return token;
  }
  restore(token) {
    const snapshot = snapshots.get(token);
    if (!snapshot) throw new Error("Unknown snapshot");
    this.#value = snapshot.value;
  }
}

const counter = new Counter();
counter.increment();
const token = counter.save();
counter.increment();
counter.increment();
console.log(counter.value, token, Object.keys(token));
counter.restore(token);
console.log(counter.value);
try {
  counter.restore({});
} catch (err) {
  console.log(err.message);
}
Text
3 {} []
1
Unknown snapshot

The token is an empty frozen object. Callers can store it and pass it back but cannot read or forge the saved state, since the data lives in a module-private WeakMap. When the token is garbage collected, so is its entry, which avoids leaks.

The caretaker: a bounded undo history

The caretaker owns the list of mementos and decides when to save and which to restore, without inspecting them.

history.mjsJavaScript
class History {
  #undo = [];
  #redo = [];
  #limit;

  constructor(originator, { limit = 3 } = {}) {
    this.originator = originator;
    this.#limit = limit;
  }

  checkpoint() {
    this.#undo.push(this.originator.save());
    if (this.#undo.length > this.#limit) this.#undo.shift();
    this.#redo.length = 0;
  }

  undo() {
    const memento = this.#undo.pop();
    if (!memento) return false;
    this.#redo.push(this.originator.save());
    this.originator.restore(memento);
    return true;
  }

  redo() {
    const memento = this.#redo.pop();
    if (!memento) return false;
    this.#undo.push(this.originator.save());
    this.originator.restore(memento);
    return true;
  }
}

class Doc {
  text = "";
  save() {
    return { text: this.text };
  }
  restore(m) {
    this.text = m.text;
  }
}

const doc = new Doc();
const history = new History(doc, { limit: 3 });

for (const word of ["one", "two", "three", "four", "five"]) {
  history.checkpoint();
  doc.text += ` ${word}`;
}
console.log(JSON.stringify(doc.text));

history.undo();
history.undo();
console.log(JSON.stringify(doc.text));
history.redo();
console.log(JSON.stringify(doc.text));
console.log(history.undo(), history.undo(), history.undo());
console.log(JSON.stringify(doc.text));
Text
" one two three four five"
" one two three"
" one two three four"
true true false
" one two"

The limit of three means only the three most recent snapshots survive: after five edits the oldest two were dropped. Two undos return to one two three, a redo moves forward one step, then three undo attempts consume the last two stored snapshots and the third fails with false, leaving one two. Bounding the stack matters, because every memento holds a full copy of the state, so an unlimited history of a big document grows without limit.

Snapshots with structuredClone

For plain data you do not need a class. structuredClone makes a deep copy that works as a memento, as described in the prototype pattern post.

clone.mjsJavaScript
const state = { items: [{ sku: "A1", qty: 1 }], coupon: null };
const snapshots = [];

function checkpoint() {
  snapshots.push(structuredClone(state));
}
function rollback() {
  const previous = snapshots.pop();
  if (previous) Object.assign(state, previous);
}

checkpoint();
state.items.push({ sku: "B2", qty: 3 });
state.coupon = "SAVE10";
console.log(state.items.length, state.coupon);

rollback();
console.log(state.items.length, state.coupon);
Text
2 SAVE10
1 null

This is the pragmatic memento for data objects. The pattern's extra structure earns its place only when the state is private, when it includes things structuredClone cannot copy, such as functions and class instances with behavior, or when the originator knows a cheaper way to save, such as storing only what changed.

Saving only the difference

A full copy per snapshot is wasteful when edits are small. Two cheaper approaches exist. Store a diff, the minimal description of what changed, and apply it in reverse to undo. Or use immutable updates with structural sharing, so each version is a new object that reuses the unchanged parts of the old one, and a snapshot is just a reference to the old version.

sharing.mjsJavaScript
let state = { user: { name: "Ada" }, cart: { items: ["A1", "B2"] }, ui: { theme: "dark" } };
const versions = [state];

state = { ...state, ui: { ...state.ui, theme: "light" } };
versions.push(state);

console.log(versions[0].ui.theme, versions[1].ui.theme);
console.log(versions[0].cart === versions[1].cart);
Text
dark light
true

The two versions share cart and user without copying them, and a memento costs almost nothing. This is how Redux time travel and Immer work. It requires disciplined immutability, since a single in-place mutation corrupts every version that shares the object.

Memento versus command for undo

Both support undo, so choose by the shape of your problem.

MementoCommand
What is storedA snapshot of stateThe operation and its inverse
Memory useOne copy per snapshotSmall per action
Undo isRestore the snapshotRun the inverse operation
Good whenOperations have no clean inverse, or state is smallOperations are small and reversible

Large systems combine them: commands for fine-grained edits, and mementos taken before heavy operations such as "apply filter to the whole image", where computing an inverse is hard.

Pitfalls

Shallow snapshots. Saving { ...state } copies one level, so nested arrays and objects are shared and later edits change the snapshot. Deep copy, or use immutable updates.

Stale restores. Restoring a snapshot overwrites everything since. If other parts of the system changed, for instance a server saved the document, the restore can bring back data that is no longer true. Define what a restore means for external state.

Unbounded growth. Limit the history, or snapshot less often, for example when the user pauses typing.

Leaking internals. If the memento exposes mutable references to the originator's own objects, the caretaker can corrupt them. Copy on save and on restore.

Sensitive data. Snapshots of forms may contain passwords or personal data. If you persist them to localStorage, you are writing that data to disk. Decide what is allowed in a draft.

Where the advice stops

If your state is plain data and a deep copy is cheap, structuredClone or immutable updates do the job with no ceremony. If your operations have clean inverses and you also want an action log, use commands. Use a real memento when state is private to a class and must stay that way, when restoring needs to bring back things outsiders cannot see and when you want a clear boundary between who creates snapshots and who stores them.

Persisting mementos

Snapshots become more useful when they survive a page reload or a crash. Drafts in a browser editor are the common case: save a memento to localStorage or IndexedDB every few seconds, and offer to restore it the next time the user opens the document. For that, the memento must be serializable, which rules out functions and class instances, and it should carry a version number so a newer release of the application can recognize and migrate or discard an old draft. Be careful about what goes into storage, since drafts can include personal data, and clear them once the real save succeeds.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.