Add and Remove at the Ends

In the overview, you saw Priya’s scorekeeper add points, undo a round, remove a player, and redraw the totals after every click. Each of those clicks starts by changing an array. New round adds a round to the end of one, and Undo last round takes it off again.

You’ll learn the array methods that add and remove items at either end, and the ones that answer “Is it there?” and “Where is it?” You’ll be able to predict what each call hands back and what the array holds afterward. Start with the order of tonight’s games, the first list Priya needs.

Get Ready to Experiment

This course continues Priya’s game night page, where the guest list, Check in buttons, and arrival bar already work. You’ll keep the page’s data in arrays, draw the page from them, and finish by building the scorekeeper.

You need the JavaScript basics, including arrays, objects, and functions, and a page that reacts to clicks. Type along with text lessons like this one, watch the videos for what moves on the page, and test your code in the exercise that ends each section.

Your experiments go in scratch/main.js, Priya’s script. Set it up like this:

  1. In VS Code, open the folder that holds scratch, and start Live Preview on scratch/index.html with Live Preview: Show Preview (External Browser) from the Command Palette.
  2. In Chrome or Edge, check that the address starts with http:// and ends with /scratch/index.html. If Live Preview opened another browser, copy the address into Chrome or Edge.
  3. Open the Console with Ctrl+Shift+J, or Cmd+Option+J on macOS.

If you’re starting here, create a scratch folder with these three files, Priya’s guest list as the second section picks it up. The page loads main.js as a module:

Language: HTML Filename: scratch/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Game Night</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Priya's Game Night</h1>
  <main>
    <h2>Who's Coming</h2>
    <ul id="players"></ul>
    <div id="arrival-bar"></div>
  </main>
  <script type="module" src="main.js"></script>
</body>
</html>

Then the stylesheet:

Language: CSS Filename: scratch/style.css
#players li {
  display: flex;
  gap: 0.5rem;
}

#players li.new {
  color: crimson;
  font-weight: bold;
}

#players li[hidden] {
  display: none;
}

#players li.arrived {
  background-color: #dcfce7;
}

#arrival-bar {
  height: 0.5rem;
  width: 0;
  background-color: seagreen;
}

And the script, which draws a row and a Check in button for each guest:

Language: JavaScript Filename: scratch/main.js
const players = [
  { id: "amara", name: "Amara", isNew: false, party: 1 },
  { id: "jonas", name: "Jonas", isNew: true, party: 1 },
  { id: "wei", name: "Wei", isNew: false, party: 2 },
  { id: "sam", name: "Sam", isNew: true, party: 1 },
];
const playerList = document.querySelector("#players");
let arrived = 0;

function showArrivals() {
  const count =
    document.querySelectorAll("#players li.arrived").length;
  const share = (count / players.length) * 100;
  const bar = document.querySelector("#arrival-bar");
  bar.style.width = share + "%";
}

function drawPlayers() {
  playerList.replaceChildren();
  for (const player of players) {
    const item = document.createElement("li");
    const name = document.createElement("span");
    name.textContent = player.name;
    item.append(name);
    const button = document.createElement("button");
    button.textContent = "Check in " + player.name;
    button.dataset.playerId = player.id;
    button.dataset.party = player.party;
    button.addEventListener("click", () => {
      button.disabled = true;
      item.classList.add("arrived");
      showArrivals();
      arrived = arrived + Number(button.dataset.party);
      console.log("Checked in:", button.dataset.playerId);
      console.log("Arrived so far:", arrived);
    });
    item.append(button);
    if (player.isNew) {
      item.classList.add("new");
    }
    playerList.append(item);
  }
}

drawPlayers();

Then install Live Preview, Microsoft’s free VS Code extension. Open the Extensions view with Ctrl+Shift+X, or Cmd+Shift+X on macOS, search for Live Preview, and click Install. Now follow the three steps above.

You should see four guests under Who’s Coming, with Jonas and Sam in crimson bold. Clicking Check in Wei turns his row light green, grows a green bar to a quarter of the width, and logs Checked in: wei and Arrived so far: 2. Reload to start fresh.

Add each experiment below drawPlayers();, and replace only your own lines when you replace one.

You’ll check every call with a labeled console.log() line: save, reload, and read the Console. The page loads main.js as a module, so the Console can’t see its names; don’t type them there. A later section explains why. Before each save, predict what the new call returns and what the array holds afterward.

Line Up Tonight’s Games

Priya’s guests play several games in an evening, and someone always asks what’s next. Priya keeps the answer in a queue: an array of game names where the game at index 0 is played next, and new suggestions join at the end.

A shop queue works the same way: people join at the back and are served from the front. The comparison stops at the numbers: nobody in a shop renumbers themselves when someone leaves, but every remaining array item moves down one index.

To add a game at the end, you call push(). You may know it already, but what does it return? Add these lines:

Language: JavaScript Filename: scratch/main.js
const queue = ["Azul", "Ticket to Ride"];
console.log("push returned:", queue.push("Carcassonne"));
console.log("Queue:", queue);

Predict what push() returns and what queue holds, then save, reload, and compare:

Language: Program Output
push returned: 3
Queue: (3) ['Azul', 'Ticket to Ride', 'Carcassonne']

The call did two things. It changed queue itself, which now ends with Carcassonne, and it returned the array’s new length, 3, not the array. That’s why every method in this lesson raises the same question: Does it change the array, and what does it return?

A const array can still change: const keeps queue naming the same array, not its contents the same. Read the one-line preview of each logged array. If you expand it with its triangle, Chrome shows what the array holds when you expand it, not when the line ran, and marks it with a small blue “i” icon.

Sam has to leave early, so the guests agree to play Codenames, a fifteen-minute game, first. To add at the front, use unshift(). Add two lines below the others:

Language: JavaScript Filename: scratch/main.js
console.log("unshift returned:", queue.unshift("Codenames"));
console.log("Queue:", queue);

Save and reload. The whole file runs again, so the new lines come last:

Language: Program Output
push returned: 3
Queue: (3) ['Azul', 'Ticket to Ride', 'Carcassonne']
unshift returned: 4
Queue: (4) ['Codenames', 'Azul', 'Ticket to Ride', 'Carcassonne']

Like push(), unshift() returned the new length, 4. Every game moved up one index to make room at index 0.

When the guests sit down to play, the game at the front leaves the queue. That’s shift(). Add two more lines:

Language: JavaScript Filename: scratch/main.js
console.log("shift returned:", queue.shift());
console.log("Queue:", queue);

The two newest lines are at the end:

Language: Program Output
push returned: 3
Queue: (3) ['Azul', 'Ticket to Ride', 'Carcassonne']
unshift returned: 4
Queue: (4) ['Codenames', 'Azul', 'Ticket to Ride', 'Carcassonne']
shift returned: Codenames
Queue: (3) ['Azul', 'Ticket to Ride', 'Carcassonne']

The shift() call returned the game it took off, Codenames, so your code knows which game has started. Azul moved down to index 0 as the next game.

For more practice, the button below opens a conversation with the AI mentor. It gives you calls one at a time, and you predict each result before it checks:

Undo the Last Round

The scorekeeper’s Undo last round button needs the opposite order to a queue: it takes back the round added most recently. An array used that way is a stack: you add to the end with push() and take from the end with pop(), so the last item in is the first one out.

A stack of plates works like this: you add and take from the top. The comparison breaks down at reading: you can’t reach the bottom plate without lifting the others, but you can read any array item.

Here’s a stack of each round’s winner in a quick game. This experiment skips the push() return values, logs the stack, and undoes one round. Replace your experiment:

Language: JavaScript Filename: scratch/main.js
const winners = [];
winners.push("Amara");
winners.push("Wei");
winners.push("Jonas");
console.log("Winners:", winners);
console.log("pop returned:", winners.pop());
console.log("Winners:", winners);

The Console shows the stack before and after the undo:

Language: Program Output
Winners: (3) ['Amara', 'Wei', 'Jonas']
pop returned: Jonas
Winners: (2) ['Amara', 'Wei']

The pop() call removed and returned the name of the most recent winner, Jonas, so an undo can say whose win it took back.

At the end of the evening, Priya wants the winners as one line she can read out, and an array isn’t text. The join() method returns the items as one string, with the separator you pass between them. Add two lines:

Language: JavaScript Filename: scratch/main.js
console.log("Shown:", winners.join(", "));
console.log("Winners:", winners);

The two new lines show a string and an untouched array:

Language: Program Output
Winners: (3) ['Amara', 'Wei', 'Jonas']
pop returned: Jonas
Winners: (2) ['Amara', 'Wei']
Shown: Amara, Wei
Winners: (2) ['Amara', 'Wei']

Before an undo, it helps to see whose win would go: the last item, read without removing it. The at() method returns the item at an index, and a negative index counts back from the end, so -1 means the last item. Add one line:

Language: JavaScript Filename: scratch/main.js
console.log("Next undo:", winners.at(-1));

The new last line names Wei’s round without removing it:

Language: Program Output
Winners: (3) ['Amara', 'Wei', 'Jonas']
pop returned: Jonas
Winners: (2) ['Amara', 'Wei']
Shown: Amara, Wei
Winners: (2) ['Amara', 'Wei']
Next undo: Wei

You could write winners[winners.length - 1], but at(-1) says what it means.

What if someone clicks Undo last round once too often? Add these lines:

Language: JavaScript Filename: scratch/main.js
winners.pop();
winners.pop();
console.log("Empty pop returned:", winners.pop());
console.log("Next undo now:", winners.at(-1));
console.log("Winners:", winners);

The two plain pop() calls emptied the stack, so the third had nothing to take:

Language: Program Output
Winners: (3) ['Amara', 'Wei', 'Jonas']
pop returned: Jonas
Winners: (2) ['Amara', 'Wei']
Shown: Amara, Wei
Winners: (2) ['Amara', 'Wei']
Next undo: Wei
Empty pop returned: undefined
Next undo now: undefined
Winners: []

Calling pop() on an empty array returns undefined without an error, so your code has to notice the undefined itself. The shift() method does the same on an empty queue, and at() returns undefined for any index outside the array.

Ask Whether a Game Is Queued

Sooner or later, a guest asks whether their favorite game is coming up, and where. Two methods answer that without changing the array.

The includes() method returns true or false. The indexOf() method returns the index of the first match, or -1 when there’s none, because array positions start at zero.

Priya’s code will ask these from several places, such as removing a vetoed game in the next lesson, so wrap each search in a small function named for what it asks. Replace your experiment:

Language: JavaScript Filename: scratch/main.js
const queue = ["Codenames", "Azul", "Ticket to Ride"];
const isQueued = (name) => queue.includes(name);
const positionOf = (name) => queue.indexOf(name);
console.log("Azul queued?", isQueued("Azul"));
console.log("Catan queued?", isQueued("Catan"));

Predict both answers, then save and reload:

Language: Program Output
Azul queued? true
Catan queued? false

A true doesn’t say how long the wait is. Add two lines that ask where, and predict their output before you save:

Language: JavaScript Filename: scratch/main.js
console.log("Azul at index:", positionOf("Azul"));
console.log("Catan at index:", positionOf("Catan"));

The positions come last:

Language: Program Output
Azul queued? true
Catan queued? false
Azul at index: 1
Catan at index: -1

Catan isn’t in the queue, so positionOf() returned -1. Treat that -1 as “not found,” never as a position. If you pass it to at(), you’ll get the last game in the queue, with no error to warn you.

Do the functions keep up when the queue changes? Add two lines at the end that start the first game with shift() and ask again:

Language: JavaScript Filename: scratch/main.js
queue.shift();
console.log("Codenames queued?", isQueued("Codenames"));

Save, and the last line answers:

Language: Program Output
Azul queued? true
Catan queued? false
Azul at index: 1
Catan at index: -1
Codenames queued? false

Each call searches queue as it is at that moment, so after the shift(), isQueued() sees that Codenames has left.

If you’re unsure which search method a task needs, describe the task to the mentor and let it check your choice:

Here’s how each method answers the lesson’s question:

Method Changes the array? Returns
push(item) Yes, adds at the end The new length
pop() Yes, removes the last item The removed item, or undefined if empty
unshift(item) Yes, adds at the front The new length
shift() Yes, removes the first item The removed item, or undefined if empty
includes(item) No true or false
indexOf(item) No The index, or -1
at(index) No The item at that index, or undefined if out of range
join(separator) No One string

Keep the first three lines of your last experiment and delete the rest, so the queue is back to Codenames, Azul, and Ticket to Ride. Jonas wants Azul out of tonight’s queue, but it sits in the middle, where no end method reaches. In Cut and Copy Parts of an Array, you’ll take it out and copy a shortlist from the queue.

Become a Member to join the conversation.