JavaScript 44 · Save a Mission and Check It on Reload

JavaScript lesson 44 of 50 · Expert projects · About 35 minutes

Keep a player's mission progress in the browser and recover it safely.

Pip watches six little cloud creatures gather safely in the glow of the restored wind beacon at dawn.
Mission Save a versioned record, validate incoming values, and rebuild Pip's progress.

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.

Record. Store the mission code and command list. → Validate. Check the version, types, and possible values. → Restore. Replay the commands through the rules.
Record → Validate → Restore

Understand the JavaScript in this lesson

Language to look for JSON.parse, JSON.stringify, localStorage, Optional chaining, Validation, try/catch.

1. Save the smallest record that tells the story

A save stores the mission seed, battery capacity, version, and list of legal moves. The current room and pickups can be calculated from those inputs. JSON.stringify turns the object into text so localStorage.setItem can keep it under the lesson's named key. Local storage belongs to the browser's site or file context. A private browser or local file setting may make it unavailable.

version: 1, seed: mission.seed, capacity: mission.capacity, moves

2. Read and check each field

JSON.parse converts text back to a JavaScript value. The optional chaining operator ?. gives undefined when data is null or undefined, so version checking still works. Number.isInteger checks the seed is a whole number. Array.isArray checks the moves field before .every tests each move. The || operator short-circuits as soon as one validation rule fails.

if (data?.version !== 1 ||

3. Keep a safe fallback

Missing saves, invalid JSON, newer formats, and unavailable storage all lead to null or false. The try block runs code that might throw. The catch block supplies a fallback. The interface reports the result, leaving the active game usable. The 1000-command limit gives the decoder a clear maximum amount of saved work to rebuild.

return decodeSave(localStorage.getItem(slot));

4. Rebuild from the start state

The load handler generates the same mission from the validated seed and capacity. It copies the moves with spread. replay then applies those moves from the Dock. at(-1) takes the last frame and gives render the reconstructed state. Try pressing East, saving, restarting, and loading.

state = replay(mission, moves).at(-1).state;
Follow what happens step by step
  1. East, then Save
    Mission saved, while Pip is in the WorkshopWhy The saved moves list contains east.
  2. Restart, then Load
    Workshop, 5 energy, CogWhy The engine reconstructs the same room from the stored input.

Predict before you run What happens if the save contains the text {oops?

Reveal the answer

JSON.parse throws. The decoder catches it and returns null, so the interface reports that no compatible save is available.

Complete checkpoint

HTML · the page and controls

<section id="board" tabindex="0" role="region" aria-label="Pip's rover controls" aria-describedby="how">
  <p id="how">Use the direction buttons.</p>
  <p id="status" role="status" aria-atomic="true"></p>
  <button type="button" data-move="north">North</button>
  <button type="button" data-move="east">East</button>
  <button type="button" data-move="south">South</button>
  <button type="button" data-move="west">West</button>
</section>
<p id="log" role="status" aria-atomic="true"></p>
<button type="button" id="restart">Restart mission</button>
<button type="button" id="save">Save mission</button>
<button type="button" id="load">Load mission</button>

JavaScript · the instructions

const links = {
  dock: { east: "workshop", south: "garden" },
  workshop: { west: "dock", south: "beacon" },
  garden: { north: "dock", east: "beacon" },
  beacon: { north: "workshop", west: "garden" }
};
const directions = ["north", "east", "south", "west"];
const standard = {
  seed: 1, capacity: 6,
  pickup: { workshop: 1, garden: 2 }
};
const newRun = mission => ({
  room: "dock", energy: mission.capacity, parts: 0, rescued: false
});
function step(state, command, mission) {
  if (state.rescued || state.energy === 0) return state;
  if (!directions.includes(command)) return state;
  const room = links[state.room][command];
  if (!room) return state;
  const parts = state.parts | (mission.pickup[room] ?? 0);
  return {
    room, parts,
    energy: room === "dock" ? mission.capacity : state.energy - 1,
    rescued: room === "beacon" && parts === 3
  };
}
function describe(state) {
  const names = { dock: "Sky Dock", workshop: "Workshop", garden: "Garden", beacon: "Beacon" };
  const pieces = ["none", "Cog", "Lens", "Cog + Lens"];
  const result = state.rescued ? " Cloud creatures rescued!" :
    state.energy === 0 ? " Battery empty. Restart to try again." : "";
  return names[state.room] + " | Energy " + state.energy +
    " | Parts: " + pieces[state.parts] + "." + result;
}

function makeMission(seed, capacity = 6) {
  const cleanSeed = seed >>> 0;
  const draw = (Math.imul(cleanSeed, 1664525) + 1013904223) >>> 0;
  const swap = draw >= 0x80000000;
  return {
    seed: cleanSeed, capacity,
    pickup: { workshop: swap ? 2 : 1, garden: swap ? 1 : 2 }
  };
}

const slot = "quesbo-sky-island-v1";
function decodeSave(text) {
  try {
    const data = JSON.parse(text);
    if (data?.version !== 1 ||
        !Number.isInteger(data.seed) || data.seed < 0 ||
        data.seed > 0xffffffff ||
        ![3, 4, 6].includes(data.capacity) ||
        !Array.isArray(data.moves) || data.moves.length > 1000 ||
        !data.moves.every(move => directions.includes(move))) return null;
    return data;
  } catch {
    return null;
  }
}
function readSave() {
  try {
    return decodeSave(localStorage.getItem(slot));
  } catch {
    return null;
  }
}
function writeSave(mission, moves) {
  try {
    if (moves.length > 1000) return false;
    localStorage.setItem(slot, JSON.stringify({
      version: 1, seed: mission.seed, capacity: mission.capacity, moves
    }));
    return true;
  } catch {
    return false;
  }
}

function replay(mission, moves) {
  return moves.reduce((frames, command) => {
    const previous = frames.at(-1).state;
    const state = step(previous, command, mission);
    frames.push({ command, state, changed: state !== previous });
    return frames;
  }, [{ command: "start", state: newRun(mission), changed: false }]);
}

const status = document.querySelector("#status");
const log = document.querySelector("#log");
let mission = makeMission(1);
let state;
let moves;
function render() {
  status.textContent = describe(state);
}
function startRun(nextMission) {
  mission = nextMission;
  state = newRun(mission);
  moves = [];
  log.textContent = "";
  render();
}
function move(command) {
  const next = step(state, command, mission);
  if (next === state) {
    log.textContent = "Pip stays put.";
    return;
  }
  moves.push(command);
  state = next;
  log.textContent = "";
  render();
}
for (const button of document.querySelectorAll("[data-move]")) {
  button.addEventListener("click", () => move(button.dataset.move));
}
document.querySelector("#restart").addEventListener("click", () => startRun({ ...mission }));
startRun(mission);
document.querySelector("#save").addEventListener("click", () => {
  log.textContent = writeSave(mission, moves) ? "Mission saved." : "Saving is unavailable.";
});
document.querySelector("#load").addEventListener("click", () => {
  const data = readSave();
  if (!data) {
    log.textContent = "No compatible save is available.";
    return;
  }
  startRun(makeMission(data.seed, data.capacity));
  moves = [...data.moves];
  state = replay(mission, moves).at(-1).state;
  render();
  log.textContent = "Saved mission loaded.";
});

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–19
Lines 1–6 const links = { dock: { east: "workshop", south: "garden" }, workshop: { west: "dock", south: "beacon" }, garden: { north: "dock", east: "beacon" }, beacon: { north: "workshop", west: "garden" } };
Set up links. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 7 const directions = ["north", "east", "south", "west"];
Set up directions. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Lines 8–11 const standard = { seed: 1, capacity: 6, pickup: { workshop: 1, garden: 2 } };
Set up standard. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Lines 12–14 const newRun = mission => ({ room: "dock", energy: mission.capacity, parts: 0, rescued: false });
Set up newRun. Keep this name attached to the same value. The arrow defines a function that this line can pass or save for later.
Line 15 function step(state, command, mission) {
Define step. The body runs when the function is called, with inputs named state, command, mission.
Line 16 if (state.rescued || state.energy === 0)
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The triple equals compares without converting the value’s type.
Line 16 return state;
Leave this function and send the value back to the caller.
Line 17 if (!directions.includes(command))
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test. Check whether the collection contains the supplied item or text.
Line 17 return state;
Leave this function and send the value back to the caller.
Line 18 const room = links[state.room][command];
Set up room. 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 19 if (!room)
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 19 return state;
Leave this function and send the value back to the caller.
Lines 20–43
Line 20 const parts = state.parts | (mission.pickup[room] ?? 0);
Set up parts. Keep this name attached to the same value. Use the right side only when the left side is null or undefined. Work out what is inside the brackets first, then use it as the key or index.
Lines 21–25 return { room, parts, energy: room === "dock" ? mission.capacity : state.energy - 1, rescued: room === "beacon" && parts === 3 };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Line 27 function describe(state) {
Define describe. The body runs when the function is called, with inputs named state.
Line 28 const names = { dock: "Sky Dock", workshop: "Workshop", garden: "Garden", beacon: "Beacon" };
Set up names. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
Line 29 const pieces = ["none", "Cog", "Lens", "Cog + Lens"];
Set up pieces. Keep this name attached to the same value. Square brackets create an ordered array. Its first position is 0.
Lines 30–31 const result = state.rescued ? " Cloud creatures rescued!" : state.energy === 0 ? " Battery empty. Restart to try again." : "";
Set up result. Keep this name attached to the same value. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Lines 32–33 return names[state.room] + " | Energy " + state.energy + " | Parts: " + pieces[state.parts] + "." + result;
Leave this function and send the value back to the caller. Plus adds numbers or joins text, depending on its values. Work out what is inside the brackets first, then use it as the key or index.
Line 36 function makeMission(seed, capacity = 6) {
Define makeMission. The body runs when the function is called, with inputs named seed, capacity = 6.
Line 37 const cleanSeed = seed >>> 0;
Set up cleanSeed. Keep this name attached to the same value. Shift the bits right and fill the spaces on the left with zeros.
Line 38 const draw = (Math.imul(cleanSeed, 1664525) + 1013904223) >>> 0;
Set up draw. Keep this name attached to the same value. Shift the bits right and fill the spaces on the left with zeros. Plus adds numbers or joins text, depending on its values.
Line 39 const swap = draw >= 0x80000000;
Set up swap. Keep this name attached to the same value. Check whether the first is greater than or equal to the second.
Lines 40–43 return { seed: cleanSeed, capacity, pickup: { workshop: swap ? 2 : 1, garden: swap ? 1 : 2 } };
Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Before the question mark comes a test. Choose the value after ? when true, or the value after : when false.
Lines 46–63
Line 46 const slot = "quesbo-sky-island-v1";
Set up slot. Keep this name attached to the same value.
Line 47 function decodeSave(text) {
Define decodeSave. The body runs when the function is called, with inputs named text.
Line 48 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 49 const data = JSON.parse(text);
Set up data. Keep this name attached to the same value. Turn JSON text into values. Invalid JSON throws an error.
Lines 50–55 if (data?.version !== 1 || !Number.isInteger(data.seed) || data.seed < 0 || data.seed > 0xffffffff || ![3, 4, 6].includes(data.capacity) || !Array.isArray(data.moves) || data.moves.length > 1000 || !data.moves.every(move => directions.includes(move)))
Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. Check whether the first value is greater than the second.
Line 55 return null;
Leave this function and send the value back to the caller.
Line 56 return data;
Leave this function and send the value back to the caller.
Line 57 catch {
Run this block if the try block throws an error.
Line 58 return null;
Leave this function and send the value back to the caller.
Line 61 function readSave() {
Define readSave. The body runs when the function is called.
Line 62 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 63 return decodeSave(localStorage.getItem(slot));
Leave this function and send the value back to the caller. Call decodeSave with the values inside the parentheses.
Lines 64–86
Line 64 catch {
Run this block if the try block throws an error.
Line 65 return null;
Leave this function and send the value back to the caller.
Line 68 function writeSave(mission, moves) {
Define writeSave. The body runs when the function is called, with inputs named mission, moves.
Line 69 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 70 if (moves.length > 1000)
Run this part when the test is truthy. Check whether the first value is greater than the second. Read how many items or characters there are.
Line 70 return false;
Leave this function and send the value back to the caller.
Lines 71–73 localStorage.setItem(slot, JSON.stringify({ version: 1, seed: mission.seed, capacity: mission.capacity, moves }));
Write text under one key in this browser’s local storage.
Line 74 return true;
Leave this function and send the value back to the caller.
Line 75 catch {
Run this block if the try block throws an error.
Line 76 return false;
Leave this function and send the value back to the caller.
Line 80 function replay(mission, moves) {
Define replay. The body runs when the function is called, with inputs named mission, moves.
Lines 81–86 return moves.reduce((frames, command) => { const previous = frames.at(-1).state; const state = step(previous, command, mission); frames.push({ command, state, changed: state !== previous }); return frames; }, [{ command: "start", state: newRun(mission), changed: false }]);
Leave this function and send the value back to the caller. Combine the entries into a single result, one entry at a time.
Lines 89–101
Line 89 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 90 const log = document.querySelector("#log");
Set up log. Keep this name attached to the same value. Find the first element matching the CSS selector. A missing match gives null.
Line 91 let mission = makeMission(1);
Set up mission. Give this name a starting value that later code can change. Call makeMission with the values inside the parentheses.
Line 92 let state;
Set up state. Give this name a starting value that later code can change.
Line 93 let moves;
Set up moves. Give this name a starting value that later code can change.
Line 94 function render() {
Define render. The body runs when the function is called.
Line 95 status.textContent = describe(state);
Call describe with the values inside the parentheses. Replace the element’s displayed text. The browser treats the value as text.
Line 97 function startRun(nextMission) {
Define startRun. The body runs when the function is called, with inputs named nextMission.
Line 98 mission = nextMission;
Store the result in the name or property to the left.
Line 99 state = newRun(mission);
Call newRun with the values inside the parentheses. Store the result in the name or property to the left.
Line 100 moves = [];
Square brackets create an ordered array. Its first position is 0. Store the result in the name or property to the left.
Line 101 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Lines 102–116
Line 102 render();
Call render with the values inside the parentheses.
Line 104 function move(command) {
Define move. The body runs when the function is called, with inputs named command.
Line 105 const next = step(state, command, mission);
Set up next. Keep this name attached to the same value. Call step with the values inside the parentheses.
Line 106 if (next === state) {
Run this part when the test is truthy. The triple equals compares without converting the value’s type.
Line 107 log.textContent = "Pip stays put.";
Replace the element’s displayed text. The browser treats the value as text.
Line 108 return;
Leave this function immediately.
Line 110 moves.push(command);
Add entries to the end of the array and return its new length.
Line 111 state = next;
Store the result in the name or property to the left.
Line 112 log.textContent = "";
Replace the element’s displayed text. The browser treats the value as text.
Line 113 render();
Call render with the values inside the parentheses.
Line 115 for (const button of document.querySelectorAll("[data-move]")) {
Take one value at a time from this sequence and run the body with it.
Line 116 button.addEventListener("click", () => move(button.dataset.move));
Register a function the browser should call when the named event happens.
Lines 118–131
Line 118 document.querySelector("#restart").addEventListener("click", () => startRun({ ...mission }));
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 119 startRun(mission);
Call startRun with the values inside the parentheses.
Line 120 document.querySelector("#save").addEventListener("click", () => {
This function body is passed as an input. 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 121 log.textContent = writeSave(mission, moves) ? "Mission saved." : "Saving is unavailable.";
Before the question mark comes a test. Choose the value after ? when true, or the value after : when false. Replace the element’s displayed text. The browser treats the value as text.
Line 123 document.querySelector("#load").addEventListener("click", () => {
This function body is passed as an input. 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 124 const data = readSave();
Set up data. Keep this name attached to the same value. Call readSave with the values inside the parentheses.
Line 125 if (!data) {
Run this part when the test is truthy. The exclamation mark reverses a true-or-false test.
Line 126 log.textContent = "No compatible save is available.";
Replace the element’s displayed text. The browser treats the value as text.
Line 127 return;
Leave this function immediately.
Line 129 startRun(makeMission(data.seed, data.capacity));
Call startRun with the values inside the parentheses.
Line 130 moves = [...data.moves];
Square brackets create an ordered array. Its first position is 0. Three dots unpack the existing entries here.
Line 131 state = replay(mission, moves).at(-1).state;
Call replay with the values inside the parentheses. Call replay(mission, moves).at with the values inside the parentheses.
Lines 132–133
Line 132 render();
Call render with the values inside the parentheses.
Line 133 log.textContent = "Saved mission loaded.";
Replace the element’s displayed text. The browser treats the value as text.

Mission challenge

After a valid save, inspect the record in browser developer tools and predict what changes if its version becomes 2.

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