JavaScript 22 · Copy Pip’s game state safely

JavaScript lesson 22 of 50 · Intermediate · About 30 minutes

Use destructuring and spread to keep a clean before-and-after record of Pip’s moves.

At the workshop, Pip reaches toward a glowing crystal battery beside a copper coil, a gear and a map of the floating islands.
Mission Update a state object without editing the previous snapshot.

Get ready

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

Unpack. Read selected properties with destructuring. → Spread. Bring old values into a new object. → Override. Write changed values after the copy.
Unpack → Spread → Override

Understand the JavaScript in this lesson

Language to look for Object destructuring, Object spread, Property order, Shallow copies.

1. Unpack only the names you need

const { room, energy } = state is object destructuring. It reads the properties named room and energy and creates local names with those values. The braces describe which properties to take. This is a shorter way to read state.room and state.energy when the function uses them more than once.

const { room, energy } = state;

2. Copy first and change second

The dots in ...state spread the top-level properties into a new object. JavaScript reads the entries from left to right. The later room and energy entries replace their earlier values in this new copy. Properties that do not appear again, such as rescued, carry over automatically.

return { ...state, room: destination, energy: energy - 1 };

3. Check whether an inner item is shared

A spread copy is shallow. It copies the property values, and an array value can still point to the same array. The last comparison checks the identity of both bag arrays. That is safe while the move only updates the room and energy. When you want to add a part, make a fresh bag too, which the next lesson will do.

console.log("Bag shared:", first.bag === moved.bag);
Follow what happens step by step
  1. Unpack room and energy
    room is Hub and energy is 5.Why The names match the state properties.
  2. Copy and override
    Workshop and 4 become the new values.Why Properties later in the literal win.
  3. Compare the bag arrays
    The comparison prints true.Why The move copied the reference to the same array.

Predict before you run What happens if you put ...state after room and energy?

Reveal the answer

The original room and energy would override your new values. In this literal, the later property wins.

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 };
}
const first = makeState();
const moved = move(first, "Workshop");
console.log("Before:", first.room, first.energy);
console.log("After:", moved.room, moved.energy);
console.log("Same rover object:", first === moved);
console.log("Bag shared:", first.bag === moved.bag);

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 const first = makeState();
Set up first. Keep this name attached to the same value. Call makeState with the values inside the parentheses.
Line 20 const moved = move(first, "Workshop");
Set up moved. Keep this name attached to the same value. Call move with the values inside the parentheses.
Line 21 console.log("Before:", first.room, first.energy);
Show a message or value in the output. Use it to watch the game work.
Lines 22–24
Line 22 console.log("After:", moved.room, moved.energy);
Show a message or value in the output. Use it to watch the game work.
Line 23 console.log("Same rover object:", first === moved);
Show a message or value in the output. Use it to watch the game work.
Line 24 console.log("Bag shared:", first.bag === moved.bag);
Show a message or value in the output. Use it to watch the game work.

Mission challenge

Copy a state with a different energy but the same room. Use === to check that the two objects are different.

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