Find a course

Module 3: Arrays and ObjectsLesson 5 of 1112 min

Arrays for Enemies, Items and High Scores

Keep lists of enemies, inventory items and high scores in arrays, read items by index, add and remove them and loop over every element.

Step 1 of 10Learn

One variable, many values

A space shooter might have 30 asteroids on screen. Creating asteroid1, asteroid2, all the way to asteroid30 would be miserable, and you couldn't easily add a 31st when one splits in two. Games need a way to store lists, and JavaScript's list is the array:

let inventory = ["sword", "shield", "potion"];
let highScores = [980, 750, 620, 400];

Square brackets create the array, and commas separate the elements. Each element has a numbered position called its index, and the first index is 0, not 1:

inventory[0]   // "sword"
inventory[2]   // "potion"
inventory[3]   // undefined (there is no fourth item)

The number of elements is inventory.length, which is 3 here. Because indexes start at 0, the last element is always at index length - 1. Forgetting that minus one, and asking for inventory[inventory.length], is so common it has a name: the off-by-one error.

You can also change an element by assigning to its index. inventory[1] = "golden shield"; replaces the second item. Arrays can hold any type of value: numbers, strings, Booleans, even other arrays or objects. A game level map is often an array of arrays, one inner array per row of tiles.

An array as numbered boxes: inventory holds sword at index 0, shield at index 1, potion at index 2; length is 3 and index 3 is undefined"sword"index 0"shield"index 1"potion"index 2undefinedindex 3inventory.length === 3The first index is 0, the last is length - 1

Step 2 of 10Practice · Choose one

Given let colors = ["red", "green", "blue", "gold"];, what is colors[colors.length - 1]?

Step 3 of 10Learn

Adding and removing items

Game lists change constantly. Enemies spawn and get destroyed, items get picked up and used. Arrays come with built-in methods for this:

  • push(item) adds to the end: inventory.push("map");
  • pop() removes and returns the last item.
  • unshift(item) adds to the start, and shift() removes the first item.
  • splice(index, 1) removes one item at a given index: enemies.splice(2, 1); removes the third enemy.
  • includes(item) returns true if the item is in the array: inventory.includes("key").
  • indexOf(item) returns the item's index, or -1 if it's not there.

A locked-door rule becomes easy to read:

if (inventory.includes("key")) {
  openDoor();
}

High score tables use sort. For numbers, you must give sort a comparison function, because by default it sorts as text, which puts 1000 before 200 (the character "1" comes before "2"):

highScores.sort((a, b) => b - a);   // biggest first

Then keep only the top five with highScores = highScores.slice(0, 5);. The slice method copies part of an array without changing the original.

Array methods by position: unshift adds to the start and shift removes from the start; push adds to the end and pop removes from the endABCDunshift(x)shift()push(x)pop()start ← array → endsplice(i, 1) removes from the middle · includes(x) checks

Step 4 of 10Practice · Match the pairs

Match each game action to the array method that performs it.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. A new enemy appears at the end of the list
  2. Check if the player owns a key
  3. Remove the enemy at position 4
  4. Take the last arrow out of the quiver
  5. Order scores from highest to lowest

Step 5 of 10Learn

Looping over an array

Arrays and loops are best friends. To do something to every element, loop through the indexes from 0 up to length - 1:

for (let i = 0; i < enemies.length; i++) {
  moveEnemy(enemies[i]);
}

Using i < enemies.length means the loop automatically adjusts when enemies are added or destroyed. You never hard-code the number.

When you don't need the index, the for...of loop is shorter and harder to get wrong:

for (const enemy of enemies) {
  moveEnemy(enemy);
}

Loops also answer questions about a list. How many coins are worth more than 50? What's the total value of the inventory? What's the highest score? Each uses the same pattern: start with a variable before the loop, update it inside.

let best = highScores[0];
for (const s of highScores) {
  if (s > best) best = s;
}

(JavaScript also has Math.max(...highScores) for this exact job, but writing it yourself once shows how it works.)

One trap: removing items with splice while looping forward skips the item that slides into the removed slot. Games usually loop backward when removing, from length - 1 down to 0, so removals don't affect the items still to be checked.

Step 6 of 10Practice · Chart

highScores = [980, 750, 620, 400]

Which index is highScores[highScores.length - 1]?

Tap the bar that answers the question, then press Check.

highScores = [980, 750, 620, 400]Bar chart with 4 categories: index 0: 980; index 1: 750; index 2: 620; index 3: 400.02004006008001,000index 0index 1index 2index 3980750620400
A loop that tracks the best value so far would end with 980.
highScores = [980, 750, 620, 400]
Itemscore
index 0980
index 1750
index 2620
index 3400

Step 7 of 10Note

Step 8 of 10Practice · Code challenge

Write countAbove(scores, limit) that returns how many numbers in the array scores are greater than limit. For example, countAbove([10, 60, 75, 20], 50) returns 2.

Runs in a sandbox in your browser.
  • countAbove([10, 60, 75, 20], 50)
  • countAbove([5, 5, 5], 5)
  • countAbove([100, 200, 300], 0)
  • countAbove([], 10)

Step 9 of 10Practice · True or false

After let s = [300, 1000, 25]; s.sort();, the array is [25, 300, 1000].

Step 10 of 10Practice · Fill in the blanks

Fill in the blanks

To add "potion" to the end of the inventory array, write inventory.("potion"). The index of the first element in any array is .