JavaScript 31 · Draw a map in rows and columns

JavaScript lesson 31 of 50 · Advanced · About 5 minutes

Draw a playable 5-by-4 map for Pip's next rescue and describe Pip's location in words.

Three cloud creatures follow Pip across lighted floating platforms toward the wind beacon in a rainstorm.
Mission Draw a playable 5-by-4 map for Pip's next rescue and describe Pip's location in words.

Get ready

New chapter. Draw a map, find routes and keep controls responsive. Start with this complete version of Pip’s mission, then compare it with the last chapter’s project.

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.

Coordinate pair. Pip starts at x = 0, y = 0. → Visit every tile. The loops walk across one row at a time. → Draw symbols. Pip, landmarks and dots form the map.
Coordinate pair → Visit every tile → Draw symbols

Understand the JavaScript in this lesson

Language to look for coordinates, nested loops, textContent, nullish coalescing.

1. Give the map two directions

Read x as the column and y as the row. The Hub is at the top left, where both values are zero. Moving right increases x, and moving down increases y. The coordinate object stores Pip's current location without storing any display symbols.

let state = { x: 0, y: 0 };

2. Put one loop inside another

The outside loop starts a new line for each row. The inside loop visits each column in that row. The condition x < columns stops before column five, so the visited x values are zero through four. The expression x += 1 adds one after each visit.

for (let x = 0; x < columns; x += 1)

3. Choose one symbol per square

The condition before ? asks whether Pip is on this square. The value after ? is used when the answer is true. Otherwise JavaScript looks up the landmark, and ?? chooses a dot when the lookup has no value. Using textContent writes plain text into the board.

line.push(hasPip ? "P" : (landmarks[label] ?? "."));

4. Read the board out loud

Join adds spaces between the tiles and a newline between the rows. The pre element preserves those spaces and line breaks. The status line adds one to x and y so players read column one and row one, and role=status lets assistive technology announce the text. The visual grid is hidden from screen readers so players can use the written position.

board.textContent = lines.join("\n");
Follow what happens step by step
  1. Run the checkpoint
    P appears in the first tile.Why The two starting coordinates are zero.
  2. Look at the bottom right
    B appears in the corner.Why The landmark lookup finds key 4,3.

Predict before you run If x is 4 and y is 0, what named place does Pip cover?

Reveal the answer

The Workshop, on the last column of the top row.

Complete checkpoint

HTML · the page and controls

<main id="sky" tabindex="0" aria-label="Sky Island Rescue board">
  <h2>Sky Island Rescue</h2>
  <p id="legend">P = Pip, H = Hub, W = Workshop, G = Garden, B = Beacon, # = rock, . = open sky.</p>
  <pre id="board" aria-hidden="true"></pre>
  <p id="status" role="status"></p>
</main>

JavaScript · the instructions

const stage = document.querySelector("#sky");
const board = document.querySelector("#board");
const status = document.querySelector("#status");
const columns = 5;
const rows = 4;
const landmarks = {
  "0,0": "H", "4,0": "W", "0,3": "G", "4,3": "B"
};
let state = { x: 0, y: 0 };
function render() {
  const lines = [];
  for (let y = 0; y < rows; y += 1) {
    const line = [];
    for (let x = 0; x < columns; x += 1) {
      const label = `${x},${y}`;
      const hasPip = x === state.x && y === state.y;
      line.push(hasPip ? "P" : (landmarks[label] ?? "."));
    }
    lines.push(line.join(" "));
  }
  board.textContent = lines.join("\n");
  const position = `Pip is at column ${state.x + 1}, row ${state.y + 1}.`;
  status.textContent = position;
}
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–14
Line 1 const stage = document.querySelector("#sky");
Set up stage. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 2 const board = document.querySelector("#board");
Set up board. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 3 const status = document.querySelector("#status");
Set up status. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 4 const columns = 5;
Set up columns. Keep this name attached to the same value.
Line 5 const rows = 4;
Set up rows. Keep this name attached to the same value.
Lines 6–8 const landmarks = { "0,0": "H", "4,0": "W", "0,3": "G", "4,3": "B" };
Set up landmarks. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 9 let state = { x: 0, y: 0 };
Set up state. Give this name a starting value that later code can change. Braces create an object. Properties give names to the stored values.
Line 10 function render() {
Define render. The body runs when the function is called.
Line 11 const lines = [];
Set up lines. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 12 for (let y = 0; y < rows; y += 1) {
Set up the counter, check the condition and run the body. Update the counter after each pass.
Line 13 const line = [];
Set up line. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Line 14 for (let x = 0; x < columns; x += 1) {
Set up the counter, check the condition and run the body. Update the counter after each pass.
Lines 15–25
Line 15 const label = `${x},${y}`;
Set up label. Keep this name attached to the same value. The backticks keep the text together. JavaScript fills each ${…} gap with a value.
Line 16 const hasPip = x === state.x && y === state.y;
Set up hasPip. Keep this name attached to the same value. JavaScript evaluates the right side only when the left side is truthy. The triple equals compares without converting the value’s type.
Line 17 line.push(hasPip ? "P" : (landmarks[label] ?? "."));
Add entries to the end of the array and return its new length.
Line 19 lines.push(line.join(" "));
Add entries to the end of the array and return its new length.
Line 21 board.textContent = lines.join("\n");
Combine array entries into a string, with the chosen separator between entries. Replace the element’s displayed text. The browser treats the value as text.
Line 22 const position = `Pip is at column ${state.x + 1}, row ${state.y + 1}.`;
Set up position. Keep this name attached to the same value. The backticks keep the text together. JavaScript fills each ${…} gap with a value.
Line 23 status.textContent = position;
Replace the element’s displayed text. The browser treats the value as text.
Line 25 render();
Call render with the values inside the parentheses.

Mission challenge

Set the starting coordinate to x = 3 and y = 2. Predict the readable position and check it. Then restore the Hub start for the next lesson.

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