GameSpark/Tutorials Open editor ↗
JavaScript · Lesson 10

Arrays: more power

The for loop works, but arrays come with built-in tools that do a job to every item in one short line — no counter, no [i]. Each one takes a little function that runs for each item.

💡

The item => { … } you’ll see below is a quick arrow function: item is the parameter (one item from the list), and the block is what to do with it. When it’s a single expression, like n => n * 2, the result is returned automatically.

1. forEach — do something with each

.forEach(fn) runs your function once for every item, handing it the item. This draws each dot without a counter or length:

let dots = [{ x: 30, y: 40 }, { x: 64, y: 84 }, { x: 98, y: 50 }];

function draw() {
  cls(1);
  dots.forEach(d => {
    circfill(d.x, d.y, 4, 9);
  });
}

Compare that to a for loop — same result, less bookkeeping.

2. map — make a new list

.map(fn) builds a new array by transforming each item. Here every score becomes its doubled value:

let scores = [1, 5, 3];
let doubled = scores.map(n => n * 2);   // [2, 10, 6]

function draw() {
  cls(1);
  print('' + doubled[0] + ' ' + doubled[1] + ' ' + doubled[2], 8, 8, 7);
}

The original scores is untouched — map always returns a fresh list.

3. filter — keep only some

.filter(fn) returns a new array of just the items whose test is true. This is the classic way to drop things that have left the screen — keep only the bullets still on it:

let bullets = [{ y: -5 }, { y: 40 }, { y: 130 }, { y: 90 }];

function draw() {
  cls(1);
  let onScreen = bullets.filter(b => b.y >= 0 && b.y < 128);
  print('kept ' + onScreen.length + ' of ' + bullets.length, 8, 8, 7);
}
🎯

In a real game you’d reassign the list to shrink it: bullets = bullets.filter(b => b.y < 128) throws away every bullet that fell off the bottom, so your loop has less to do each frame.

What you learned