JavaScript 15 · Build a map with routes and state

JavaScript lesson 15 of 50 · Early intermediate · About 35 minutes

Create a small route map and make Pip remember the current location.

Pip pauses where stone paths branch toward a crystal-roof workshop, a hanging garden and a distant beacon.
Mission Change Pip’s location only when the chosen destination is listed as a valid route.

Get ready

Open Complete checkpoint below. For a browser preview, put the HTML in your editor’s HTML panel and the JavaScript in its JavaScript panel. For a local file, put the HTML first in a new .html file, then put the JavaScript between <script> and </script> at the end. Save the file and open it in a browser.

Match the HTML to the JavaScript. HTML tags create the game’s controls and text. An id names one element. The code uses that name to find the element. A class groups elements for styling, while a data- attribute can carry a game value. A status area with aria-live lets compatible screen readers announce updates.

Read the state. Start with Pip’s current place. → Check the map. Allow only a listed neighbour. → Update and render. Store the new place, then show it.
Read the state → Check the map → Update and render

Understand the JavaScript in this lesson

Language to look for objects and keys, bracket lookup, includes, state, spread syntax, render function.

1. Store the route map as data

The braces hold an object. Each key is a place, and its value is an array of places you can reach in one move. Use quotes for a key with a space, such as Sky Dock. This makes the rules visible in one place. To make a two-way trail, list each end in the other end’s neighbours.

const routes = {
  "Sky Dock": ["Workshop", "Garden"],
  Workshop: ["Sky Dock", "Beacon"],
  Garden: ["Sky Dock", "Beacon"],
  Beacon: ["Workshop", "Garden"]
};

2. Keep the location in state

State means facts about the game right now. The object begins with one property, place. The const declaration fixes which object state refers to. It still lets you update a property such as state.place. The display reads that property each time render() runs.

const state = { place: "Sky Dock" };

3. Look up a route using the current place

Square brackets let JavaScript use the value of state.place as a key. routes[state.place] finds the matching array of neighbours. includes(destination) checks that array. The exclamation mark reverses the result so the branch catches blocked moves and return ends the function early.

if (!routes[state.place].includes(destination)) {

4. Update the data before the page

The click handler changes state.place only after the route passes its check. Then render() puts the new location into the separate place display. The square brackets and three dots in the button lookup copy the list of matching elements into an array. In later lessons we can use its positions for shortcuts.

const moveButtons = [...document.querySelectorAll("[data-destination]")];
Follow what happens step by step
  1. At Sky Dock, choose Beacon.
    No route from Sky Dock to Beacon.Why Beacon is not a direct neighbour of the dock.
  2. Choose Workshop, then Beacon.
    The location display shows Beacon.Why Each move is connected to the location immediately before it.

Predict before you run What happens if you put Beacon in Sky Dock’s list but leave Sky Dock out of Beacon’s list?

Reveal the answer

Pip can make that direct journey only towards Beacon. The program looks up routes separately for each starting place.

Complete checkpoint

HTML · the page and controls

<section aria-labelledby="mission-title">
  <h2 id="mission-title">Sky Island Rescue · Island mission</h2>
  <p>Location: <span id="place"></span></p>
  <button type="button" data-destination="Sky Dock">Sky Dock</button>
  <button type="button" data-destination="Workshop">Workshop</button>
  <button type="button" data-destination="Garden">Garden</button>
  <button type="button" data-destination="Beacon">Beacon</button>
  <p id="report" role="status">Choose a connected destination.</p>
</section>

JavaScript · the instructions

const routes = {
  "Sky Dock": ["Workshop", "Garden"],
  Workshop: ["Sky Dock", "Beacon"],
  Garden: ["Sky Dock", "Beacon"],
  Beacon: ["Workshop", "Garden"]
};

const state = { place: "Sky Dock" };

const moveButtons = [...document.querySelectorAll("[data-destination]")];

function showMessage(message) {
  document.querySelector("#report").textContent = message;
}

function render() {
  document.querySelector("#place").textContent = state.place;
}

function travel(event) {
  const destination = event.currentTarget.dataset.destination;
  if (!routes[state.place].includes(destination)) {
    showMessage("No route from " + state.place + " to " + destination + ".");
    return;
  }
  state.place = destination;
  render();
  showMessage("Pip reaches " + destination + ".");
}

for (const button of moveButtons) {
  button.addEventListener("click", travel);
}
render();

Read the JavaScript line by line

Open a small group of lines while you read the complete checkpoint. Blank lines separate ideas. Closing braces mark the end of a block. An ellipsis here means you can read the rest in the full program.

Lines 1–24
Lines 1–6 const routes = { "Sky Dock": ["Workshop", "Garden"], Workshop: ["Sky Dock", "Beacon"], Garden: ["Sky Dock", "Beacon"], Beacon: ["Workshop", "Garden"] };
Set up routes. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
Line 8 const state = { place: "Sky Dock" };
Set up state. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 10 const moveButtons = [...document.querySelectorAll("[data-destination]")];
Set up moveButtons. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0. Three dots unpack the existing entries here.
Line 12 function showMessage(message) {
Define showMessage. The body runs when the function is called, with inputs named message.
Line 13 document.querySelector("#report").textContent = message;
Replace the element’s displayed text. The browser treats the value as text.
Line 16 function render() {
Define render. The body runs when the function is called.
Line 17 document.querySelector("#place").textContent = state.place;
Replace the element’s displayed text. The browser treats the value as text.
Line 20 function travel(event) {
Define travel. The body runs when the function is called, with inputs named event.
Line 21 const destination = event.currentTarget.dataset.destination;
Set up destination. Keep this name attached to the same value.
Line 22 if (!routes[state.place].includes(destination)) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test. Work out what is inside the brackets first, then use it as the key or index.
Line 23 showMessage("No route from " + state.place + " to " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 24 return;
Leave this function immediately.
Lines 26–34
Line 26 state.place = destination;
Store the result in the name or property to the left.
Line 27 render();
Call render with the values inside the parentheses.
Line 28 showMessage("Pip reaches " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 31 for (const button of moveButtons) {
Take one value at a time from this sequence and run the body with it.
Line 32 button.addEventListener("click", travel);
Register a function the browser should call when the named event happens.
Line 34 render();
Call render with the values inside the parentheses.

Mission challenge

Add a direct Workshop–Garden trail in both directions. Test the whole trip from Sky Dock to Beacon through those two places.

Change one piece at a time. Run the checkpoint again and compare what you expected with what actually happened.