JavaScript lesson 20 of 50 · Early intermediate · About 45 minutes
Finish the first browser game with a restart button and a mission test plan.

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.

Understand the JavaScript in this lesson
Language to look for state factory, reassigning let, function composition, reset state, testing a game path.
1. Create a fresh mission object
A factory function makes a fresh object every time you call it. freshMission() creates a new place, battery value, empty inventory array and false rescue flag in one place. Because the array literal is inside the function, a second mission gets its own empty array. This prevents old cargo from returning after a restart.
function freshMission() {
return { place: "Sky Dock", energy: MAX_ENERGY, inventory: [], rescued: false };
}
2. Let the state name point to a new object
let lets the restart function change which object state refers to. During a game, small changes update properties such as state.place. Restart has a bigger job, so it assigns the complete result of freshMission() and then calls render().
let state = freshMission();
3. Draw and announce the reset
The render function reads the new state to update the location, energy, inventory and disabled controls. Then showMessage() reports the new mission. Focus goes to the Workshop control, the second destination in the array. Players who activated Restart using a keyboard can carry on from a useful position.
moveButtons[1].focus();
4. Test the game the way people play it
First check one rejected route, then collect and rescue. Watch the energy and inventory as you go. Test restarting after a win as well as before a win. Each listener is wired up once, so there should be one move per click during the second mission. Keep these tests when you add features in later lessons.
document.querySelector("#reset").addEventListener("click", restart);-
Go Workshop, collect Cog, go Sky Dock, go Garden and collect Lens.
The bag contains Cog, Lens. Energy is 3.Why Three valid moves have cost one unit each and pickups cost nothing. -
Go Beacon and activate it.
The creatures are safe. Energy is 2.Why Both parts are present and the Beacon is the current location. -
Press Restart and inspect the display.
Sky Dock, 6 energy, Empty, movement enabled.Why A new object replaced the old state and render read the fresh values.
Predict before you run Would setting only state.place = "Sky Dock" make a full restart?
Reveal the answer
It would move Pip back to Sky Dock, but old energy, cargo and the rescue flag would still be stored. Replacing the complete state resets all four together.
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>
<p id="shortcuts">Keyboard shortcuts 1–4 go to the matching destinations. Regular button controls also work.</p>
<button type="button" data-destination="Sky Dock">1. Sky Dock</button>
<button type="button" data-destination="Workshop">2. Workshop</button>
<button type="button" data-destination="Garden">3. Garden</button>
<button type="button" data-destination="Beacon">4. Beacon</button>
<button id="charge" type="button">Recharge at Sky Dock</button>
<button id="collect" type="button">Collect the local part</button>
<button id="rescue" type="button">Activate the Beacon</button>
<button id="reset" type="button">Restart the mission</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 needed = ["Cog", "Lens"];
function freshMission() {
return { place: "Sky Dock", energy: MAX_ENERGY, inventory: [], rescued: false };
}
let state = freshMission();
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";
for (const button of moveButtons) button.disabled = state.rescued;
document.querySelector("#charge").disabled = state.rescued;
document.querySelector("#collect").disabled = state.rescued;
document.querySelector("#rescue").disabled = state.rescued;
}
function travel(event) {
const destination = event.currentTarget.dataset.destination;
if (state.rescued) return;
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." : "Restart the mission from Sky Dock."));
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 + ".");
}
function rescue() {
if (state.place !== "Beacon") {
showMessage("Travel to the Beacon first.");
return;
}
const ready = needed.every(part => state.inventory.includes(part));
if (!ready) {
showMessage("The Beacon needs both the Cog and the Lens.");
return;
}
state.rescued = true;
render();
showMessage("Beacon lit. The cloud creatures are safe!");
}
function handleShortcut(event) {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat) return;
if (event.target.closest("input, textarea, select, [contenteditable]")) return;
const keys = ["1", "2", "3", "4"];
const index = keys.indexOf(event.key);
if (index === -1) return;
const button = moveButtons[index];
if (!button.disabled) button.click();
}
function restart() {
state = freshMission();
render();
showMessage("A new mission begins at Sky Dock.");
moveButtons[1].focus();
}
for (const button of moveButtons) {
button.addEventListener("click", travel);
}
document.querySelector("#charge").addEventListener("click", recharge);
document.querySelector("#collect").addEventListener("click", collect);
document.querySelector("#rescue").addEventListener("click", rescue);
document.querySelector("#reset").addEventListener("click", restart);
document.querySelector("section[aria-labelledby=mission-title]").addEventListener("keydown", handleShortcut);
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–27
-
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 needed = ["Cog", "Lens"]; - Set up needed. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
-
Line 14
function freshMission() { - Define freshMission. The body runs when the function is called.
-
Line 15
return { place: "Sky Dock", energy: MAX_ENERGY, inventory: [], rescued: false }; - Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Square brackets create an ordered array. Its first position is 0.
-
Line 18
let state = freshMission(); - Set up state. Give this name a starting value that later code can change. Call freshMission with the values inside the parentheses.
-
Line 20
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 22
function showMessage(message) { - Define showMessage. The body runs when the function is called, with inputs named message.
-
Line 23
document.querySelector("#report").textContent = message; - Replace the element’s displayed text. The browser treats the value as text.
-
Line 26
function render() { - Define render. The body runs when the function is called.
-
Line 27
document.querySelector("#place").textContent = state.place; - Replace the element’s displayed text. The browser treats the value as text.
Lines 28–39
-
Line 28
document.querySelector("#energy").textContent = state.energy; - Replace the element’s displayed text. The browser treats the value as text.
-
Line 29
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 30
for (const button of moveButtons) - Take one value at a time from this sequence and run the body with it.
-
Line 30
button.disabled = state.rescued; - Store the result in the name or property to the left.
-
Line 31
document.querySelector("#charge").disabled = state.rescued; - Store the result in the name or property to the left.
-
Line 32
document.querySelector("#collect").disabled = state.rescued; - Store the result in the name or property to the left.
-
Line 33
document.querySelector("#rescue").disabled = state.rescued; - Store the result in the name or property to the left.
-
Line 36
function travel(event) { - Define travel. The body runs when the function is called, with inputs named event.
-
Line 37
const destination = event.currentTarget.dataset.destination; - Set up destination. Keep this name attached to the same value.
-
Line 38
if (state.rescued) - Run this part when the test is truthy.
-
Line 38
return; - Leave this function immediately.
-
Line 39
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.
Lines 40–55
-
Line 40
showMessage("No route from " + state.place + " to " + destination + "."); - Call showMessage with the values inside the parentheses.
-
Line 41
return; - Leave this function immediately.
-
Line 43
if (state.energy === 0) { - Run this part when the test is truthy. The triple equals compares without converting the value’s type.
-
Line 44
showMessage("No energy left. " + (state.place === "Sky Dock" ? "Recharge to travel." : "Restart the mission from Sky Dock.")); - Call showMessage with the values inside the parentheses.
-
Line 45
return; - Leave this function immediately.
-
Line 47
state.energy -= 1; - Update the existing value with the operation shown.
-
Line 48
state.place = destination; - Store the result in the name or property to the left.
-
Line 49
render(); - Call render with the values inside the parentheses.
-
Line 50
showMessage("Pip reaches " + destination + "."); - Call showMessage with the values inside the parentheses.
-
Line 53
function recharge() { - Define recharge. The body runs when the function is called.
-
Line 54
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 55
showMessage("Recharge is only available at Sky Dock."); - Call showMessage with the values inside the parentheses.
Lines 56–71
-
Line 56
return; - Leave this function immediately.
-
Line 58
state.energy = MAX_ENERGY; - Store the result in the name or property to the left.
-
Line 59
render(); - Call render with the values inside the parentheses.
-
Line 60
showMessage("Pip’s battery is full."); - Call showMessage with the values inside the parentheses.
-
Line 63
function collect() { - Define collect. The body runs when the function is called.
-
Line 64
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 65
if (!part) { - Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
-
Line 66
showMessage("There is no part here."); - Call showMessage with the values inside the parentheses.
-
Line 67
return; - Leave this function immediately.
-
Line 69
if (state.inventory.includes(part)) { - Run this part when the test is truthy. Check whether the collection contains the supplied item or text.
-
Line 70
showMessage("Pip already has the " + part + "."); - Call showMessage with the values inside the parentheses.
-
Line 71
return; - Leave this function immediately.
Lines 73–88
-
Line 73
state.inventory.push(part); - Add entries to the end of the array and return its new length.
-
Line 74
render(); - Call render with the values inside the parentheses.
-
Line 75
showMessage("Pip collects the " + part + "."); - Call showMessage with the values inside the parentheses.
-
Line 78
function rescue() { - Define rescue. The body runs when the function is called.
-
Line 79
if (state.place !== "Beacon") { - Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
-
Line 80
showMessage("Travel to the Beacon first."); - Call showMessage with the values inside the parentheses.
-
Line 81
return; - Leave this function immediately.
-
Line 83
const ready = needed.every(part => state.inventory.includes(part)); - Set up ready. Keep this name attached to the same value. Check whether every array entry passes the test.
-
Line 84
if (!ready) { - Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
-
Line 85
showMessage("The Beacon needs both the Cog and the Lens."); - Call showMessage with the values inside the parentheses.
-
Line 86
return; - Leave this function immediately.
-
Line 88
state.rescued = true; - Store the result in the name or property to the left.
Lines 89–99
-
Line 89
render(); - Call render with the values inside the parentheses.
-
Line 90
showMessage("Beacon lit. The cloud creatures are safe!"); - Call showMessage with the values inside the parentheses.
-
Line 93
function handleShortcut(event) { - Define handleShortcut. The body runs when the function is called, with inputs named event.
-
Line 94
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.repeat) - Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy.
-
Line 94
return; - Leave this function immediately.
-
Line 95
if (event.target.closest("input, textarea, select, [contenteditable]")) - Run this part when the test is truthy. Look for the nearest matching element, starting at this element and then its ancestors.
-
Line 95
return; - Leave this function immediately.
-
Line 96
const keys = ["1", "2", "3", "4"]; - Set up keys. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
-
Line 97
const index = keys.indexOf(event.key); - Set up index. Keep this name attached to the same value. Find the first matching index, or return -1 when nothing matches.
-
Line 98
if (index === -1) - Run this part when the test is truthy. The triple equals compares without converting the value’s type.
-
Line 98
return; - Leave this function immediately.
-
Line 99
const button = moveButtons[index]; - Set up button. Keep this name attached to the same value. Work out what is inside the brackets first, then use it as the key or index.
Lines 100–115
-
Line 100
if (!button.disabled) - Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
-
Line 100
button.click(); - Call button.click with the values inside the parentheses.
-
Line 103
function restart() { - Define restart. The body runs when the function is called.
-
Line 104
state = freshMission(); - Call freshMission with the values inside the parentheses. Store the result in the name or property to the left.
-
Line 105
render(); - Call render with the values inside the parentheses.
-
Line 106
showMessage("A new mission begins at Sky Dock."); - Call showMessage with the values inside the parentheses.
-
Line 107
moveButtons[1].focus(); - Work out what is inside the brackets first, then use it as the key or index. Give this control keyboard focus.
-
Line 110
for (const button of moveButtons) { - Take one value at a time from this sequence and run the body with it.
-
Line 111
button.addEventListener("click", travel); - Register a function the browser should call when the named event happens.
-
Line 113
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 114
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 115
document.querySelector("#rescue").addEventListener("click", rescue); - 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.
Lines 116–118
-
Line 116
document.querySelector("#reset").addEventListener("click", restart); - 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 117
document.querySelector("section[aria-labelledby=mission-title]").addEventListener("keydown", handleShortcut); - 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 118
render(); - Call render with the values inside the parentheses.
Mission challenge
Try a second full rescue with the parts collected in the opposite order. Restart in the middle and check that neither part survives the reset.
Change one piece at a time. Run the checkpoint again and compare what you expected with what actually happened.