Looping over arrays

Topic 2 of 4 in Arrays6 min readBeginnerFree course

Overview

Most array work means visiting each item: printing it, adding it up, checking it, changing it. You have three everyday tools:

  • a for…of loop, when you want to do something with each item;
  • forEach, the same idea written as a method call;
  • question methods — find, some, every and friends — when you’re looking for something.

The next topic adds map, filter and reduce, for building new arrays and values.

for…of

JavaScript
const scores = [8, 6, 9];
for (const score of scores) {
  console.log(score);
}

It’s short, readable, and you can use break, continue and even await inside it. When in doubt, start here.

Need the index too? Use entries():

JavaScript
for (const [i, score] of scores.entries()) {
  console.log(`#${i + 1}: ${score}`);
}

The classic for loop

The counting loop from Loops still has its uses — for example when you need to step by two, go backwards, or compare neighbouring items:

JavaScript
for (let i = scores.length - 1; i >= 0; i--) {
  console.log(scores[i]); // backwards
}

for (let i = 1; i < scores.length; i++) {
  const change = scores[i] - scores[i - 1]; // compare with the previous item
  console.log(change);
}

forEach

forEach calls a function for every item, passing the item, its index and the whole array:

JavaScript
scores.forEach((score, i) => console.log(i, score));

It suits short, one-line actions and fits naturally at the end of a chain of array methods:

JavaScript
users.filter((u) => u.active).forEach((u) => sendReminder(u));

You can’t break out of forEach. If you might stop early, use for…of or one of the methods below.

Two more forEach gotchas:

  • It always returns undefined. If you want a new array, use map instead.
  • It doesn’t wait for async callbacks. items.forEach(async (i) => await save(i)) starts all the saves at once and moves on immediately. Use for…of with await to do them one at a time.

Asking questions

JavaScript
const lessons = [
  { title: 'Loops', minutes: 6 },
  { title: 'Closures', minutes: 9 },
];

lessons.find((l) => l.minutes > 8);       // { title: 'Closures', … }
lessons.findIndex((l) => l.title === 'Loops'); // 0
lessons.some((l) => l.minutes > 8);       // true  — at least one
lessons.every((l) => l.minutes < 10);     // true  — all of them

These stop as soon as they know the answer, which makes them faster than looping through everything yourself.

With minutes = [6, 9, 4, 12]: find(m => m > 8) checks 6, finds 9 and stops, returning 9. some(m => m > 10) checks all four and gets true at 12. every(m => m < 10) passes 6, 9 and 4, then fails at 12 and returns false. findIndex(m => m === 4) stops at index 2.

Method Returns When nothing matches
find(fn) the first matching item undefined
findLast(fn) the last matching item undefined
findIndex(fn) the index of the first match -1
findLastIndex(fn) the index of the last match -1
some(fn) true if at least one matches false
every(fn) true if all match true (for an empty array)
includes(value) true if the value is present (===) false

Note that every on an empty array is true — “all zero items pass” is technically true. Check length too if that matters.

find returns the real item

find gives you the actual object from the array, not a copy. Changing it changes the array’s item:

JavaScript
const lesson = lessons.find((l) => l.title === 'Loops');
lesson.minutes = 7;
lessons[0].minutes; // 7

Don’t change the array while looping

Adding or removing items while you’re looping over the same array leads to skipped or repeated items:

JavaScript
const nums = [1, 2, 2, 3];
for (let i = 0; i < nums.length; i++) {
  if (nums[i] === 2) nums.splice(i, 1); // removes one 2, then skips the next!
}
console.log(nums); // [1, 2, 3]

Instead, build a new array with filter:

JavaScript
const withoutTwos = nums.filter((n) => n !== 2); // [1, 3]

Which one should I use?

You want to… Use
Do something with every item for…of (or forEach for one-liners)
Stop early, or await inside for…of
Get the first item that matches find
Know where it is findIndex
Check whether any / all match some / every
Build a new array or total map, filter, reduce (next topic)
Exercise

First unfinished topic

Return the title of the first topic whose done is false, or null if all are done. Then write allDone(list) that returns true only if every topic is done.

JavaScript
const topics = [
  { title: 'Loops', done: true },
  { title: 'Arrays', done: false },
  { title: 'Objects', done: false },
];

function nextTopic(list) {
  // your code here
}

function allDone(list) {
  // your code here
}

Summary

  • for…of is the simplest loop and supports break and continue.
  • forEach runs a callback for each item but can’t be stopped early.
  • find/findLast return an item; findIndex returns its position or -1.
  • some asks “at least one?”; every asks “all of them?” — both stop early.
  • Don’t add or remove items in an array while looping over it.