JavaScript 26 · Handle the commands that go wrong

JavaScript lesson 26 of 50 · Intermediate · About 35 minutes

Use a command dispatcher to send requests to the right game rule and catch unknown requests.

At the workshop, Pip reaches toward a glowing crystal battery beside a copper coil, a gear and a map of the floating islands.
Mission Distinguish a refused move from a malformed command.

Get ready

Open Complete checkpoint below. Paste the JavaScript into a blank JavaScript editor and run it.

Read the request. Look up the action type. → Call the rule. Each case returns one rule result. → Recover. Catch and report a malformed request.
Read the request → Call the rule → Recover

Understand the JavaScript in this lesson

Language to look for switch and case, throw, Error objects, try and catch.

1. Dispatch each action by type

The action object describes what a player wants to do. switch (action.type) reads its type once and looks at the case labels for a match. Each branch returns immediately after calling its rule, so execution does not drop into the next case. A move’s destination is a separate property passed as the next argument.

case "move": return Game.move(state, action.destination);

2. Separate a blocked move from a mistake

A blocked move is an ordinary game result and the move rule returns the same state. An unknown action type points to a problem in the code that built the action. If none of the cases match, default uses throw to stop this function. new Error creates an object with a message that explains the problem.

default: throw new Error("Unknown action: " + action.type);

3. Recover at the call site

The try block runs normally until an error is thrown. JavaScript skips the rest of that block and starts the matching catch block. error is the catch block’s local name for the error object. You can read its message and let the program keep running after the block.

} catch (error) {
  console.log("Recovered:", error.message);
}
Follow what happens step by step
  1. Try move to Beacon
    The old state is returned.Why The move action is known, but the route is blocked.
  2. Try teleport
    The catch prints its error message.Why No case recognizes teleport, so default throws.
  3. Continue after catch
    Still running prints Hub.Why The outer script recovered without changing the state.

Predict before you run Would the try block catch an ordinary blocked move?

Reveal the answer

The catch body only runs if something throws. A blocked move returns normally, so catch would not run.

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 apply(state, action) {
  switch (action.type) {
    case "move": return Game.move(state, action.destination);
    case "collect": return Game.collect(state);
    case "repair": return Game.repair(state);
    default: throw new Error("Unknown action: " + action.type);
  }
}
const first = Game.makeState();
const blocked = apply(first, { type: "move", destination: "Beacon" });
console.log("Blocked move kept state:", blocked === first);
try {
  apply(first, { type: "teleport", destination: "Beacon" });
} catch (error) {
  console.log("Recovered:", error.message);
}
console.log("Still running:", first.room);

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–32
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 apply(state, action) {
Define apply. The body runs when the function is called, with inputs named state, action.
Lines 31–32 switch (action.type) {
Compare one value with the case labels, then follow the matching branch.
Line 32 case "move":
Run this branch when its label matches.
Lines 32–42
Line 32 return Game.move(state, action.destination);
Leave this function and send the value back to the caller. Call Game.move with the values inside the parentheses.
Line 33 case "collect":
Run this branch when its label matches.
Line 33 return Game.collect(state);
Leave this function and send the value back to the caller. Call Game.collect with the values inside the parentheses.
Line 34 case "repair":
Run this branch when its label matches.
Line 34 return Game.repair(state);
Leave this function and send the value back to the caller. Call Game.repair with the values inside the parentheses.
Line 35 default:
Use this branch when no label matches.
Line 35 throw new Error("Unknown action: " + action.type);
Stop this part of the program and report the problem to the caller or a matching catch block.
Line 38 const first = Game.makeState();
Set up first. Keep this name attached to the same value. Call Game.makeState with the values inside the parentheses.
Line 39 const blocked = apply(first, { type: "move", destination: "Beacon" });
Set up blocked. Keep this name attached to the same value. Call apply with the values inside the parentheses.
Line 40 console.log("Blocked move kept state:", blocked === first);
Show a message or value in the output. Use it to watch the game work.
Line 41 try {
Attempt these instructions. If one throws, the catch block can handle the error.
Line 42 apply(first, { type: "teleport", destination: "Beacon" });
Call apply with the values inside the parentheses.
Lines 43–46
Line 43 catch (error) {
Run this block if the try block throws an error.
Line 44 console.log("Recovered:", error.message);
Show a message or value in the output. Use it to watch the game work.
Line 46 console.log("Still running:", first.room);
Show a message or value in the output. Use it to watch the game work.

Mission challenge

Add one more known action that reports the current state. Then compare a valid request with a misspelt type.

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