Episode 1 — Fundamentals / 1.16 — Using Browser Functionalities in JavaScript

1.16.b — window.location & window.history

In one sentence: location is the current URL and a navigation lever; history is the tab’s back/forward stack — and the History API (pushState / replaceState) lets SPAs change the URL without a full document reload.

Navigation: ← 1.16.a — BOM · 1.16.c — Storage & Cookies →


1. window.location (the Location object)

Useful parts of a URL

PropertyExample (https://ex.com/app?id=1#sec)
hrefFull URL string
protocol"https:"
host"ex.com" (hostname + port if any)
hostname"ex.com"
pathname"/app"
search"?id=1"
hash"#sec"

2. Navigation with location

// Assigning href navigates (like clicking a link) — adds history entry by default
window.location.href = "https://example.com";

// Replace current entry (user cannot “Back” to previous page in some cases)
window.location.replace("https://example.com/offline.html");

// Reload (uses cache heuristics like a toolbar refresh)
window.location.reload();

For a hard reload (skip cache as much as possible), users use DevTools or browser UI — reload() has no reliable cross-browser “hard” flag in modern specs; avoid relying on deprecated boolean arguments.

location.assign(url) — like setting href. replace swaps current history entry.


3. Same-page jumps

location.hash = "section-2"; // updates hash, scrolls to id="section-2" if present

Fires hashchange (on window) when hash changes — useful for simple client-side routing.


4. window.history

Method / propertyRole
history.lengthNumber of entries in session history (not always intuitive)
history.back()Like browser Back
history.forward()Forward
history.go(n)Relative jump (-1 = back)

These respect user gesture expectations — avoid trapping users in unclosable flows (UX + security).


5. History API: pushState & replaceState

history.pushState({ page: 1 }, "", "/app/users/42");
  • Updates URL and adds a history entryno network request, no automatic scroll.
  • Your app must listen for popstate to restore UI when user clicks Back/Forward.

replaceState — same but replaces current entry (good for replacing a transient URL).

SPA routing (React Router, Vue Router, etc.) builds on these primitives plus popstate.


6. Key takeaways

  1. location exposes URL parts and navigation / reload methods.
  2. history.back() / forward() / go() mirror browser chrome.
  3. pushState / replaceState change URL without full page load — pair with popstate for correct UX.

Explain-It Challenge

Explain without notes:

  1. What is the difference between location.assign and location.replace?
  2. Why does pushState alone not load a new HTML document from the server?
  3. When should an SPA listen for popstate?

Navigation: ← 1.16.a — BOM · 1.16.c — Storage & Cookies →