How to Loop through an Array in JavaScript

Looping over an array and any other objects in JavaScript is a common problem lots of programmers encounter the most. There are several ways to loop over an array in JavaScript. Let’s have a look and find the optimal one for you.

for

The classic and famous for loop iterates over each item in the array. The for loops through a block of code a number of times:

let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

The for uses 3 expressions:

  • Initialization - initializes the loop variable with a starting value which can only be executed once.
  • Condition - specifies that the loop should stop looping
  • Final expression - is performed at the end of each loop execution. It is used to increment the index.

for...in

The for...in loops through the properties of an object. It is among the most used and straightforward methods for iterating over objects:

let person = {
  fname: "John",
  lname: "Doe",
  age: 25
};
for (let i in person) {
  console.log(person[i] + " ");
}

while

The while loops through a block of code as long as a specified condition is true:

let i = 0;
while (i < 10) {
  console.log(i);
  i++;
}

In the given example, the code in the loop will run over and over again, as long as a variable (i) is less than 10.

You can use break and continue in a while loop. But when you use the while loop you should take into account the increment for the next iteration. If you do not, then it may result in an infinite loop.

forEach()

An alternative to for and for/in loops isArray.prototype.forEach(). The forEach() runs a function on each indexed element in an array. Starting at index[0] a function will get called on index[0], index[1], index[2], etc… forEach() will let you loop through an array nearly the same way as a for loop:

let array = [{
    id: 1,
    name: 'John',
    age: 12
  },
  {
    id: 2,
    name: 'Jane',
    age: 14
  },
  {
    id: 3,
    name: 'Martin',
    age: 13
  },
  {
    id: 4,
    name: 'Katie',
    age: 17
  },
  {
    id: 5,
    name: 'Louis',
    age: 11
  }
];
array.forEach(function (profile, index, arr) {
  console.log(`Index: ${index}, Name: ${profile.name}`);
});

The forEach() is not functional, as the function it takes as the input parameter is not supposed to return a value, thus cannot be regarded as a pure function.

map()

The map() method creates a new array with the results of calling a function for each array element.

const array = [2, 3, 5, 7];
console.log(array.map(el => el * 2));

At first sight, the map() method has similarities with the forEach() method since it will also invoke the callback function once for each array element. The difference is that map() creates and returns new arrays based on the callback function result.

Do you find this helpful?

Related articles