How to Loop through an Array in JavaScript

Looping through an array JavaScript is among the most frequent things a programmer will do. An array can include many data entries, and you may wish to do a task on all the data entries. For example, you have an array of numbers you wish to calculate the summation of them, or you have an array of objects and you want to add a property to all of these objects. There are several ways to iterate over an array in JavaScript. Let’s have a look and find the optimal one for you.

for loop

The classic and famous for loop iterates over any custom range of numbers you specify and runs a block of code on each iteration. Whenever you want to iterate over an array, an straight-forward way is to have a for loop iterating over the array's keys, which means iterating over zero to the length of the array.

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

The for loop uses 3 expressions:

  1. Initialization - initializes the loop variable with a starting value which can only be executed once.
  2. Condition - specifies the situation under which the loop should be stopped.
  3. 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. You define a variable like i in for (let i in arr), and in each iteration, the variable i will become equal to a key in arr. Then you will be able to select the desired array element with something like arr[i]. See an example below.

Javascript array for..in loop
let names = ["John", "Jack", "Alice"]; for (let i in names) { console.log(names[i]); }

for...of

If you want to access the values inside an array directly, and not the keys, then you should use for...of instead of for...in.

Javascript while loop
let names = ["John", "Jack", "Alice"]; for (let i of names) { console.log(i); }

Using for...of with entries() method

This one is a bit complex. Every array has a method entries() which returns an iterable of both keys and values of an array. using for...of with this method enables us to have an iteration over both keys and values.

Javascript while loop
const names = ["John", "Jack", "Alice"]; for (const [key, value] of names.entries()) { console.log(`key: ${key}, value: ${value}`); }

while

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

How to Loop through an Array in JavaScript
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:

Javascript while 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}`); });

As you saw, the forEach() method takes a function as an input argument, and applies the function to each element of the array in a sequential way. Also note that 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. In the example below, we define an array named myFirstArray, and then multiply each element by 2 and store the result in a new array named mySecondArray. Try the code and you will notice that the first array remains unchanged.

How to Loop through an Array in JavaScript
const myFirstArray = [2, 3, 5, 7]; const mySecondArray = myFirstArray.map(el => el * 2); console.log('----myFirstArray----'); console.log(myFirstArray); console.log('----mySecondArray----'); console.log(mySecondArray);

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.