BeginnerCoder

Lesson 25 — Ultimate: hash router

Boss level: client-side routing

A single-page app (SPA) changes what is on screen without loading a new page. The simplest way is a hash router: the part of the URL after # (location.hash, e.g. #/about) picks which view to show, and the browser's hashchange event tells you when it changes. At its core a router is just a lookup table from path to handler (a function that builds the view), with a fallback for unknown paths.

window.addEventListener("hashchange", () => {
  render(location.hash.slice(1)); // "#/about" → "/about"
});

Why it matters: React Router, Vue Router and every SPA work on this idea.

Want it another way?
Task

Finish go(path): call the matching handler, or return "404" when the path is unknown. Expect About, then 404.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with JavaScript Intermediate

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.