Question presented to candidate: "You're building a single-page app's router. You call history.pushState() to change the URL as the user navigates between views, with no full page reload. Now the user clicks the browser's back button — how does your app find out, and does it correctly restore the previous view?"
What a strong answer should cover:
- 📌 Interview term:
history.pushState(state, title, url)— a real, built-in method that genuinely changes the browser's address bar URL and adds a real entry to the session history stack — with no page reload, no network request — while also storing an arbitrarystateobject associated with that specific history entry. - 📌 Interview term: the real, direct answer to the prompt — verified directly, live: calling
history.back()(the same real action the browser's own back button performs) genuinely fired a real"popstate"event onwindow, carrying the CORRECT restoredstateobject from the entry being navigated back to, andlocationgenuinely reverted to that entry's own URL — real, live proof thatpushState-based routing genuinely survives the back button. - 📌 Interview term: the real
popstatelistener responsibility — a precise answer names that the APPLICATION, not the browser, is responsible for actually re-rendering the correct view in response topopstate— the event only reports that navigation happened and hands back the storedstate; a router must readevent.stateand update the UI accordingly itself. - 📌 Interview term:
pushStatedoes NOT firepopstate— a precise answer names a real, easy-to-miss gotcha: callingpushStateitself never triggers apopstateevent — only actual back/forward navigation (via the browser UI,history.back(),history.forward(), orhistory.go()) does; a router's initial render logic must be triggered separately, not by assumingpopstatewill fire on the firstpushStatecall. - A precise answer names
history.replaceState()as the real sibling method — identical signature, but REPLACES the current history entry instead of adding a new one, useful for correcting a URL without creating an extra, unwanted back-button stop.
Clarifying questions expected:
- None — this is a definitional/practical question; directly demonstrating the real, verified back-button-triggered
popstateevent with correctly restored state is the strong signal.
Code / implementation expected: Yes — real pushState calls building up history, a real history.back() call, and a real, observed popstate event with the correctly restored state.