JavaScript 17 · Collect parts in an inventory

JavaScript lesson 17 of 50 · Early intermediate · About 40 minutes

Let Pip pick up repair parts and show what is already in the bag.

Pip pauses where stone paths branch toward a crystal-roof workshop, a hanging garden and a distant beacon.
Mission Use a map entry, an array and duplicate checks to collect Cog and Lens.

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.

Look up the place. Read the part on the current tile. → Protect the bag. Reject empty pickups and duplicates. → Show the result. Join the collected part names for the page.
Look up the place → Protect the bag → Show the result

Understand the JavaScript in this lesson

Language to look for object lookups, undefined, includes, push, join, logical OR fallback.

1. Give each repair part a home

The object partsAt pairs Workshop with Cog and Garden with Lens. The key is a place name and the value is the part at that place. Sky Dock and Beacon have no entry. This is a second way to use an object in the game: the route map holds lists of exits, and this map holds a single part name.

const partsAt = { Workshop: "Cog", Garden: "Lens" };

2. Look up the local part

The collect function uses Pip’s current place to look up a part. JavaScript returns undefined when a property is missing from this object. For this map, a part name is always a non-empty string. The !part check therefore catches locations with nothing to collect.

const part = partsAt[state.place];

3. Prevent duplicates before adding

The inventory begins as an empty array. includes(part) tells you whether the current part is already packed. Only after passing this check does push(part) add one item to the end. The same part stays in the map, but the inventory check makes it a one-time pickup.

state.inventory.push(part);

4. Display the bag clearly

join(", ") makes one line of text from the array, with a comma and space between items. An empty array joins to an empty string. In that case || supplies the word Empty for display. The actual inventory array remains available for game rules.

document.querySelector("#inventory").textContent = state.inventory.join(", ") || "Empty";
Follow what happens step by step
  1. At Sky Dock, press Collect.
    There is no part here.Why The current place does not have a partsAt entry.
  2. At Workshop, collect twice.
    The bag displays one Cog.Why The first click pushes the Cog; the second returns before push.

Predict before you run If you visit Garden first, what order will the bag show after you collect both parts?

Reveal the answer

Lens, Cog. The inventory records the order you collect them, and join displays that same order.

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>
  <p>Energy: <span id="energy"></span></p>
  <p>Inventory: <span id="inventory"></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>
  <button id="charge" type="button">Recharge at Sky Dock</button>
  <button id="collect" type="button">Collect the local part</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 MAX_ENERGY = 6;

const partsAt = { Workshop: "Cog", Garden: "Lens" };

const state = { place: "Sky Dock", energy: MAX_ENERGY, inventory: [] };

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

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

function render() {
  document.querySelector("#place").textContent = state.place;
  document.querySelector("#energy").textContent = state.energy;
  document.querySelector("#inventory").textContent = state.inventory.join(", ") || "Empty";
}

function travel(event) {
  const destination = event.currentTarget.dataset.destination;
  if (!routes[state.place].includes(destination)) {
    showMessage("No route from " + state.place + " to " + destination + ".");
    return;
  }
  if (state.energy === 0) {
    showMessage("No energy left. " + (state.place === "Sky Dock" ? "Recharge to travel." : "Reload the page to try again."));
    return;
  }
  state.energy -= 1;
  state.place = destination;
  render();
  showMessage("Pip reaches " + destination + ".");
}

function recharge() {
  if (state.place !== "Sky Dock") {
    showMessage("Recharge is only available at Sky Dock.");
    return;
  }
  state.energy = MAX_ENERGY;
  render();
  showMessage("Pip’s battery is full.");
}

function collect() {
  const part = partsAt[state.place];
  if (!part) {
    showMessage("There is no part here.");
    return;
  }
  if (state.inventory.includes(part)) {
    showMessage("Pip already has the " + part + ".");
    return;
  }
  state.inventory.push(part);
  render();
  showMessage("Pip collects the " + part + ".");
}

for (const button of moveButtons) {
  button.addEventListener("click", travel);
}
document.querySelector("#charge").addEventListener("click", recharge);
document.querySelector("#collect").addEventListener("click", collect);
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–26
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 MAX_ENERGY = 6;
Set up MAX_ENERGY. Keep this name attached to the same value.
Line 10 const partsAt = { Workshop: "Cog", Garden: "Lens" };
Set up partsAt. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 12 const state = { place: "Sky Dock", energy: MAX_ENERGY, inventory: [] };
Set up state. 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 14 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 16 function showMessage(message) {
Define showMessage. The body runs when the function is called, with inputs named message.
Line 17 document.querySelector("#report").textContent = message;
Replace the element’s displayed text. The browser treats the value as text.
Line 20 function render() {
Define render. The body runs when the function is called.
Line 21 document.querySelector("#place").textContent = state.place;
Replace the element’s displayed text. The browser treats the value as text.
Line 22 document.querySelector("#energy").textContent = state.energy;
Replace the element’s displayed text. The browser treats the value as text.
Line 23 document.querySelector("#inventory").textContent = state.inventory.join(", ") || "Empty";
JavaScript tries the right side only when the left side is falsy. Combine array entries into a string, with the chosen separator between entries.
Line 26 function travel(event) {
Define travel. The body runs when the function is called, with inputs named event.
Lines 27–42
Line 27 const destination = event.currentTarget.dataset.destination;
Set up destination. Keep this name attached to the same value.
Line 28 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 29 showMessage("No route from " + state.place + " to " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 30 return;
Leave this function immediately.
Line 32 if (state.energy === 0) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 33 showMessage("No energy left. " + (state.place === "Sky Dock" ? "Recharge to travel." : "Reload the page to try again."));
Call showMessage with the values inside the parentheses.
Line 34 return;
Leave this function immediately.
Line 36 state.energy -= 1;
Update the existing value with the operation shown.
Line 37 state.place = destination;
Store the result in the name or property to the left.
Line 38 render();
Call render with the values inside the parentheses.
Line 39 showMessage("Pip reaches " + destination + ".");
Call showMessage with the values inside the parentheses.
Line 42 function recharge() {
Define recharge. The body runs when the function is called.
Lines 43–58
Line 43 if (state.place !== "Sky Dock") {
Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
Line 44 showMessage("Recharge is only available at Sky Dock.");
Call showMessage with the values inside the parentheses.
Line 45 return;
Leave this function immediately.
Line 47 state.energy = MAX_ENERGY;
Store the result in the name or property to the left.
Line 48 render();
Call render with the values inside the parentheses.
Line 49 showMessage("Pip’s battery is full.");
Call showMessage with the values inside the parentheses.
Line 52 function collect() {
Define collect. The body runs when the function is called.
Line 53 const part = partsAt[state.place];
Set up part. Keep this name attached to the same value. Work out what is inside the brackets first, then use it as the key or index.
Line 54 if (!part) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 55 showMessage("There is no part here.");
Call showMessage with the values inside the parentheses.
Line 56 return;
Leave this function immediately.
Line 58 if (state.inventory.includes(part)) {
Run this part when the test is truthy. Check whether the collection contains the supplied item or text.
Lines 59–72
Line 59 showMessage("Pip already has the " + part + ".");
Call showMessage with the values inside the parentheses.
Line 60 return;
Leave this function immediately.
Line 62 state.inventory.push(part);
Add entries to the end of the array and return its new length.
Line 63 render();
Call render with the values inside the parentheses.
Line 64 showMessage("Pip collects the " + part + ".");
Call showMessage with the values inside the parentheses.
Line 67 for (const button of moveButtons) {
Take one value at a time from this sequence and run the body with it.
Line 68 button.addEventListener("click", travel);
Register a function the browser should call when the named event happens.
Line 70 document.querySelector("#charge").addEventListener("click", recharge);
Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 71 document.querySelector("#collect").addEventListener("click", collect);
Find the first element matching the CSS selector. A missing match gives null. Register a function the browser should call when the named event happens.
Line 72 render();
Call render with the values inside the parentheses.

Mission challenge

Collect Lens at Garden and Cog at Workshop, then test that the inventory lists both exactly once.

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