Skip to main content
JavaScript & the browser·Module C9 · Lesson 10
TaskBuild createUndoStack(key, initial) with .current() / .push(state) / .undo() / .size() per the theory. Use storage key 'doc'. Start with {text:'a'}. push({text:'ab'}). push({text:'abc'}). Log size (3), current().text ('abc'). undo() and log .text ('ab'). undo() and log .text ('a'). undo() once more — should stop, log .text ('a') again.

Capstone: undo stack with structuredClone + localStorage

275 XP15 min
Theory

Persistent undo with native primitives

A real-world feature that ties C9 ideas together:

  • structuredClone — snapshot state into the stack.
  • localStorage + JSON — persist the stack across reloads.
  • No library.
function createUndoStack(key, initial) {
  const stack = JSON.parse(localStorage.getItem(key) || "null") || [initial];
  function save() { localStorage.setItem(key, JSON.stringify(stack)); }

  return {
    current() { return stack[stack.length - 1]; },
    push(state) { stack.push(structuredClone(state)); save(); },
    undo() {
      if (stack.length > 1) stack.pop();
      save();
      return stack[stack.length - 1];
    },
    size() { return stack.length; },
  };
}

What you get

  • push(state) saves a snapshot. structuredClone means later mutations don't corrupt history.
  • undo() pops the last snapshot and returns the previous one. Stops at the initial state.
  • Reload the page and the stack is still there.

The capstone

Build that exact shape and walk through a small editing flow: start, push two states, undo once, undo once more, undo a third time (should stop at initial).

🔒

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial — card required, cancel anytime.

Sign up — free trial →

First 15 lessons in each track are free. No card needed for those.

PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.