Lesson 7 of 8

Undo, step by step

Goal

A history of snapshots that never change

01

Explanation

Undo looks like a complicated feature, but it follows directly from the "Don't mutate, make a copy" lesson: if every change produces a new array and leaves the old one alone, the old one stays an intact snapshot you can go back to whenever you like.

The history here is a stack. Before every change you push the current state onto past, and to undo you pop the last thing you pushed and put it back. You don't need a deep copy or any comparison, because you're only keeping references.

The trap is changing the state in place with push or splice. Then everything on the stack is a reference to the same array, so the "past" changes along with the present and there's nothing left to go back to.

02

Your task

Finish commit(next) so it pushes state.items onto past, puts next in its place and re-renders. Finish undo() so it restores the last snapshot from past, and make render() disable #undo when past is empty.

Checks

5 checks
  1. The undo button follows the history: disabled, then enabled, then disabled again
  2. Undo reverses an addition
  3. Undo reverses a removal too
  4. Two undos in a row go back one step at a time
  5. The restored snapshot is the same array, not a copy of it
03

Hints

0/3
Track lessons0 of 8 done

A UI is built from data, so here you learn to filter, sort and group that data without touching the DOM directly.

Intermediate level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 8 done

A UI is built from data, so here you learn to filter, sort and group that data without touching the DOM directly.

Intermediate level, 8 lessons, 2 hours in total.