Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Iterating over arrays

To iterate over an array means to do the same thing for each element: print a list, add up a total, find the most expensive product. JavaScript has several ways to do this, each convenient in its own way.

The for...of loop

The simplest way is a for...of loop. On each step the variable receives the next element of the array:

const fruits = ['apple', 'pear', 'plum'];
 
for (const fruit of fruits) {
  console.log(fruit);
}
// apple
// pear
// plum

The variable is declared with const: a new variable is created on every step, and it is not changed within the step.

Adding up elements

Iteration is often used to accumulate something. Create a variable before the loop and add the element to it on each step:

const prices = [120, 80, 300];
let total = 0;
 
for (const price of prices) {
  total += price;
}
 
console.log(total); // 500

The classic for with an index

A for loop with a counter is needed when the index itself matters: for example, to process only even positions or to compare neighbouring elements:

const fruits = ['apple', 'pear', 'plum'];
 
for (let i = 0; i < fruits.length; i++) {
  console.log(`${i}: ${fruits[i]}`);
}
// 0: apple
// 1: pear
// 2: plum

The condition i < fruits.length stops the loop at the last index.

forEach

The forEach() method calls the given function for each element. The function receives the element and its index:

const fruits = ['apple', 'pear'];
 
fruits.forEach((fruit, index) => {
  console.log(`${index + 1}. ${fruit}`);
});
// 1. apple
// 2. pear

A function passed to another function is called a callback.

Index and value in for...of

If a for...of loop also needs the index, iterate over entries(). It yields "index, element" pairs, which are unpacked into two variables right away:

const fruits = ['apple', 'pear'];
 
for (const [index, fruit] of fruits.entries()) {
  console.log(index, fruit);
}
// 0 apple
// 1 pear

Common mistake

You cannot leave forEach() early: break inside the function is a syntax error, and return only ends the current step. If the iteration has to stop, use for...of:

const numbers = [3, 8, 15, 4];
 
for (const number of numbers) {
  if (number > 10) {
    console.log(`Found: ${number}`); // Found: 15
    break;
  }
}

Thanks for reading!

Donate to the site — we work hard for you.