replaceState() vs pushState()

I've been reading and searching for advantages / disadvantages between replaceState() & pushState(). Read also Mozilla's article, and this interesting test but still is unclear to me the differences.

Any one care to explain in what they differ?


Solution 1:

replaceState() will change the URL in the browser (ie. pressing the back button won't take you back)

pushState() will change the URL, and keep the old one in the browser history (ie. pressing the back button will take you back)

Solution 2:

From your link

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.

replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.

If you simply want to update history entry, use replaceState() otherwise use pushState(), which will keep the old entry and create a new one. They're similar but both have different effects so it depends on whether or not you want to replace or create new history entries.

Think of it like I'm dealing out a deck of cards by putting one card on top of the other (face up) and you can only take the top card in the pile (i.e. the last card I dealt). Let's say I put a Jack of Hearts on the pile. Now for the next card if I use replaceState, so I take that Jack of Hearts off and put the next card on. The number of cards is the same since we just replaced the top card. If I had used pushState instead, I would've put the next card on top of the Jack of Hearts (so now both exist in the pile and the pile is one card higher).

Swap the cards in the analogy with URLs and that's how the URL history is modified.