Skip to content
FrontDepth, Home

Back to the topic

Practice: Client-side routing

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

4 predict-output · 3 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputJunior

    The code pushes two history entries with state, then calls history.back(). What does it log, and in what order?

    JavaScript
    window.addEventListener("popstate", (event) => {
      console.log("popstate " + event.state.page);
    });
    
    history.replaceState({ page: "home" }, "");
    history.pushState({ page: "list" }, "");
    history.pushState({ page: "item" }, "");
    console.log("pushed " + history.state.page);
    
    history.back();
    console.log("after back() " + history.state.page);
  2. Open questionJunior

    What happens when a user clicks a link in a multi-page app compared with a single-page app, and how does a client-side router work?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  3. Predict the outputMiddle

    A tiny router scores route patterns (static 10, dynamic 3, splat −2), tries them from the highest score down, and returns the first match with its params. What does the code log?

    JavaScript
    function score(pattern) {
      let total = 0;
      for (const segment of pattern.split("/").filter(Boolean)) {
        if (segment === "*") total -= 2;
        else if (segment.startsWith(":")) total += 3;
        else total += 10;
      }
      return total;
    }
    
    function match(pattern, pathname) {
      const parts = pattern.split("/").filter(Boolean);
      const segments = pathname.split("/").filter(Boolean);
      const params = {};
      for (let i = 0; i < parts.length; i++) {
        if (parts[i] === "*") {
          params["*"] = segments.slice(i).join("/");
          return params;
        }
        if (segments[i] === undefined) return null;
        if (parts[i].startsWith(":")) params[parts[i].slice(1)] = decodeURIComponent(segments[i]);
        else if (parts[i] !== segments[i]) return null;
      }
      return segments.length === parts.length ? params : null;
    }
    
    const routes = ["/*", "/users/:id", "/users/new", "/users/:id/*"];
    const ranked = [...routes].sort((a, b) => score(b) - score(a));
    
    function resolve(pathname) {
      for (const pattern of ranked) {
        const params = match(pattern, pathname);
        if (params) return pattern + " " + JSON.stringify(params);
      }
      return "no match";
    }
    
    console.log(ranked.join(" | "));
    console.log(resolve("/users/new"));
    console.log(resolve("/users/42"));
    console.log(resolve("/users/42/posts/7"));
    console.log(resolve("/users"));
  4. Predict the outputMiddle

    A product list keeps its filters in the URL. What does this code log in Node, which has the same URL and URLSearchParams classes as browsers?

    JavaScript
    const url = new URL("https://shop.example/products?tag=shoes&tag=sale&q=red boots");
    
    console.log(url.searchParams.get("tag"));
    console.log(url.searchParams.getAll("tag").length);
    console.log(url.searchParams.get("q"));
    console.log(url.searchParams.get("sort"));
    console.log(url.search);
    
    url.searchParams.set("page", "2");
    console.log(url.search);
    
    console.log(new URL("edit", "https://app.example/users/42").pathname);
    console.log(new URL("edit", "https://app.example/users/42/").pathname);
  5. Predict the outputSenior

    The user clicks a slow link and then, right away, a fast one. The router aborts the previous navigation when a new one starts. What does the code log?

    JavaScript
    const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
    
    const loaders = {
      "/slow": () => wait(30, "slow data"),
      "/fast": () => wait(10, "fast data"),
    };
    
    let current = null;
    let screen = "home";
    
    async function navigate(path) {
      current?.abort();
      const controller = new AbortController();
      current = controller;
      console.log("start " + path);
    
      const data = await loaders[path]();
      if (controller.signal.aborted) {
        console.log("ignored " + path);
        return;
      }
      screen = data;
      console.log("render " + screen);
    }
    
    navigate("/slow");
    navigate("/fast");
    await wait(50);
    console.log("screen " + screen);
  6. Open questionSenior

    After a client-side navigation, what must a router do about scroll, focus and announcements, and why doesn't the browser do it?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.