GameSpark/Tutorials Open editor ↗
JavaScript · Lesson 9

Arrays

One variable holds one value. An array holds a whole list of them — perfect for the many things a game juggles: bullets, enemies, coins, high scores.

1. Make a list

Write the items in square brackets, separated by commas. This array holds four x-positions, and a for loop draws a circle at each:

let xs = [24, 50, 78, 104];

function draw() {
  cls(1);
  for (let i = 0; i < xs.length; i++) {
    circfill(xs[i], 64, 5, 9);
  }
}

2. Read an item by its index

Each item has a numbered slot called its index, and counting starts at 0. So xs[0] is the first item, xs[1] the second. xs.length is how many there are:

let xs = [24, 50, 78, 104];

function draw() {
  cls(1);
  print('first: ' + xs[0], 8, 8, 7);
  print('third: ' + xs[2], 8, 20, 7);
  print('how many: ' + xs.length, 8, 32, 7);
}
💡

Because indexes start at 0, the last item is always list[list.length - 1], not list[list.length]. That off-by-one catches everyone at first.

3. Add items with push

list.push(value) adds to the end. Here a new dot appears each time you press space — the array grows while the game runs:

let dots = [];

function update() {
  if (keyp(' ')) {
    dots.push(rnd(128));   // add a random x
  }
}

function draw() {
  cls(1);
  for (let i = 0; i < dots.length; i++) {
    circfill(dots[i], 64, 4, 12);
  }
  print('press space', 34, 100, 7);
}
🎯

Try it: start xs with more numbers. Push the mouse position (mouse().x) on click instead of a random one. Add a ys array so each dot has its own height.

What you learned