Lesson 9 of 30
Why undo history and the browser back button both work the same way — the last thing you did is the first thing that gets undone.
9 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
This topic is about judgment and practical tradeoffs more than a single right answer — a mock interview is the better way to test yourself on it.
Be interviewed on this →Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Picture a stack of plates at a buffet. You can only take a plate from the top. You can only put a new plate on top, too. You can't reach into the middle and pull one out — not without knocking the whole stack over.
That's a stack as a data structure: the last thing you added is the first thing you take back out. There's a name for this order — LIFO, last in, first out — but the plate picture is really all you need to remember it.
You already use stacks constantly without thinking about it. Hit undo in a document editor, and it undoes your most recent change first, not your first change. Click the browser's back button, and it takes you to the page you were on just before this one — not all the way back to where you started browsing an hour ago. Both are stacks: every action gets "placed on top," and undoing or going back always removes from the top.
Adding to a stack is usually called push. Removing from the top is called pop. That's the entire vocabulary.
// A plain array works fine as a stack — push adds to the end (the "top"),
// pop removes from the end.
const undoHistory = [];
undoHistory.push("typed 'hello'"); // top: typed 'hello'
undoHistory.push("bolded text"); // top: bolded text
undoHistory.push("added a comma"); // top: added a comma
// Hitting "undo" pops the most recent action off the top.
const lastAction = undoHistory.pop();
console.log(lastAction); // "added a comma" — the most recent one, not the oldest
console.log(undoHistory); // ["typed 'hello'", "bolded text"]
push and pop both work on the same end. Beginners sometimes expect pop to remove from the front, like taking the oldest plate. It removes from the top — the most recently added one.A stack isn't a new type in JavaScript — it's an array you've agreed to only touch at one end, using push and pop. The genealogy tracks back to the arrays you already know from the JavaScript track; a stack is just an array with a promise attached.