JavaScript lesson 27 of 50 · Intermediate · About 40 minutes
Package Pip’s progress as JSON text and check it carefully before using it again.

Get ready
Open Complete checkpoint below. Paste the JavaScript into a blank JavaScript editor and run it. Language to look for JSON.stringify, JSON.parse, Version fields, Validation, Types. JSON is a text format for data. The code checks the room against the game’s map, the energy against an integer range and the bag against the allowed part names. A final check only accepts a successful rescue with two parts at the Beacon. The return step makes a fresh object using just the fields the engine understands and copies the bag. If a check fails, the function throws before returning. The caller can catch that problem and keep the old game rather than using broken data.
Understand the JavaScript in this lesson
1. Give the save a version
JSON.stringify turns a JavaScript object into saved text. { version: 1, state } wraps the state in a labelled container. A version number lets later code recognise this shape. JSON.parse reads the text into new JavaScript values. An incomplete string can throw before any game checks run.return JSON.stringify({ version: 1, state });2. Check structure and game rules
Object.hasOwn asks whether the map itself has the given key. Array.isArray checks that you really have an array before calling array methods. A Set drops repeated entries, so a shorter Set than bag reveals duplicates.new Set(state.bag).size !== state.bag.length ||3. Build the trusted shape
bag: [...state.bag], rescued: state.rescued
The text contains version 1 and the state.Why encode serialises both together.
A fresh state contains Workshop, four energy and coil.Why decode checks every important field before returning.
The caller catches Invalid game state.Why Ocean is not an own key of MAP.
Predict before you run Does valid JSON text always describe a playable saved game?
Reveal the answer
No. JSON checks the text format. The game’s own checks must still decide whether the values make sense.
Complete checkpoint
JavaScript · the instructions
const MAP = {
Hub: ["Workshop", "Garden"],
Workshop: ["Hub", "Garden"],
Garden: ["Hub", "Workshop", "Beacon"],
Beacon: ["Garden"]
};
const PARTS = { Workshop: "coil", Garden: "cell" };
function makeState() {
return { room: "Hub", energy: 5, bag: [], rescued: false };
}
function move(state, destination) {
const { room, energy } = state;
if (!MAP[room].includes(destination) || energy < 1) {
return state;
}
return { ...state, room: destination, energy: energy - 1 };
}
function collect(state) {
const part = PARTS[state.room];
if (!part || state.bag.includes(part)) return state;
return { ...state, bag: [...state.bag, part] };
}
function repair(state) {
if (state.room !== "Beacon") return state;
if (!["coil", "cell"].every((part) => state.bag.includes(part))) return state;
return { ...state, rescued: true };
}
const Game = Object.freeze({ makeState, move, collect, repair });
function encode(state) {
return JSON.stringify({ version: 1, state });
}
function decode(text) {
const record = JSON.parse(text);
if (record === null || record.version !== 1) {
throw new Error("Unsupported save version");
}
const state = record.state;
if (
!state ||
!Object.hasOwn(MAP, state.room) ||
!Number.isInteger(state.energy) ||
state.energy < 0 || state.energy > 5 ||
!Array.isArray(state.bag) ||
!state.bag.every((part) => part === "coil" || part === "cell") ||
new Set(state.bag).size !== state.bag.length ||
typeof state.rescued !== "boolean"
) {
throw new Error("Invalid game state");
}
if (state.rescued &&
(state.room !== "Beacon" || state.bag.length !== 2)) {
throw new Error("Invalid rescue");
}
return {
room: state.room, energy: state.energy,
bag: [...state.bag], rescued: state.rescued
};
}
const state = Game.collect(Game.move(Game.makeState(), "Workshop"));
const text = encode(state);
const loaded = decode(text);
console.log("Loaded:", loaded.room, loaded.energy, loaded.bag[0]);
try {
decode('{"version":1,"state":{"room":"Ocean","energy":99,"bag":[],"rescued":false}}');
} catch (error) {
console.log("Rejected:", error.message);
}
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–21
-
Lines 1–6
const MAP = { Hub: ["Workshop", "Garden"], Workshop: ["Hub", "Garden"], Garden: ["Hub", "Workshop", "Beacon"], Beacon: ["Garden"] }; - Set up MAP. 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 7
const PARTS = { Workshop: "coil", Garden: "cell" }; - Set up PARTS. Keep this name attached to the same value. Braces create an object. Properties give names to the stored values.
-
Line 9
function makeState() { - Define makeState. The body runs when the function is called.
-
Line 10
return { room: "Hub", energy: 5, bag: [], 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 12
function move(state, destination) { - Define move. The body runs when the function is called, with inputs named state, destination.
-
Line 13
const { room, energy } = state; - Set up { room, energy }. Keep this name attached to the same value.
-
Line 14
if (!MAP[room].includes(destination) || energy < 1) { - Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation mark reverses a true-or-false test.
-
Line 15
return state; - Leave this function and send the value back to the caller.
-
Line 17
return { ...state, room: destination, energy: energy - 1 }; - Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Three dots unpack the existing entries here.
-
Line 19
function collect(state) { - Define collect. The body runs when the function is called, with inputs named state.
-
Line 20
const part = PARTS[state.room]; - 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 21
if (!part || state.bag.includes(part)) - Run this part when the test is truthy. JavaScript tries the right side only when the left side is falsy. The exclamation mark reverses a true-or-false test.
Lines 21–34
-
Line 21
return state; - Leave this function and send the value back to the caller.
-
Line 22
return { ...state, bag: [...state.bag, part] }; - Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Three dots unpack the existing entries here.
-
Line 24
function repair(state) { - Define repair. The body runs when the function is called, with inputs named state.
-
Line 25
if (state.room !== "Beacon") - Run this part when the test is truthy. The exclamation and two equals signs check whether values differ without type conversion.
-
Line 25
return state; - Leave this function and send the value back to the caller.
-
Line 26
if (!["coil", "cell"].every((part) => state.bag.includes(part))) - Run this part when the test is truthy. The exclamation mark reverses a true-or-false test. Square brackets create an ordered array. Its first position is 0.
-
Line 26
return state; - Leave this function and send the value back to the caller.
-
Line 27
return { ...state, rescued: true }; - Leave this function and send the value back to the caller. Braces create an object. Properties give names to the stored values. Three dots unpack the existing entries here.
-
Line 29
const Game = Object.freeze({ makeState, move, collect, repair }); - Set up Game. Keep this name attached to the same value. Prevent direct edits to the properties of this object.
-
Line 30
function encode(state) { - Define encode. The body runs when the function is called, with inputs named state.
-
Line 31
return JSON.stringify({ version: 1, state }); - Leave this function and send the value back to the caller. Turn the JavaScript value into JSON text for a save or comparison.
-
Line 34
function decode(text) { - Define decode. The body runs when the function is called, with inputs named text.
Lines 35–63
-
Line 35
const record = JSON.parse(text); - Set up record. Keep this name attached to the same value. Turn JSON text into values. Invalid JSON throws an error.
-
Line 36
if (record === null || record.version !== 1) { - 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 37
throw new Error("Unsupported save version"); - Stop this part of the program and report the problem to the caller or a matching catch block.
-
Line 39
const state = record.state; - Set up state. Keep this name attached to the same value.
-
Lines 40–49
if ( !state || !Object.hasOwn(MAP, state.room) || !Number.isInteger(state.energy) || state.energy < 0 || state.energy > 5 || … - 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 50
throw new Error("Invalid game state"); - Stop this part of the program and report the problem to the caller or a matching catch block.
-
Lines 52–53
if (state.rescued && (state.room !== "Beacon" || state.bag.length !== 2)) { - Run this part when the test is truthy. JavaScript evaluates the right side only when the left side is truthy. JavaScript tries the right side only when the left side is falsy.
-
Line 54
throw new Error("Invalid rescue"); - Stop this part of the program and report the problem to the caller or a matching catch block.
-
Lines 56–59
return { room: state.room, energy: state.energy, bag: [...state.bag], rescued: state.rescued }; - 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 61
const state = Game.collect(Game.move(Game.makeState(), "Workshop")); - Set up state. Keep this name attached to the same value. Call Game.collect with the values inside the parentheses.
-
Line 62
const text = encode(state); - Set up text. Keep this name attached to the same value. Call encode with the values inside the parentheses.
-
Line 63
const loaded = decode(text); - Set up loaded. Keep this name attached to the same value. Call decode with the values inside the parentheses.
Lines 64–68
-
Line 64
console.log("Loaded:", loaded.room, loaded.energy, loaded.bag[0]); - Show a message or value in the output. Use it to watch the game work.
-
Line 65
try { - Attempt these instructions. If one throws, the catch block can handle the error.
-
Line 66
decode('{"version":1,"state":{"room":"Ocean","energy":99,"bag":[],"rescued":false}}'); - Call decode with the values inside the parentheses.
-
Line 67
catch (error) { - Run this block if the try block throws an error.
-
Line 68
console.log("Rejected:", error.message); - Show a message or value in the output. Use it to watch the game work.
Mission challenge
Write one test string with a repeated coil and one with room Hub and rescued true. Check that both are refused.
Change one piece at a time. Run the checkpoint again and compare what you expected with what actually happened.