Iterating through an array in JavaScript can be done in multiple ways. One of the most common methods is using the traditional for loop. In JavaScript, we have another modern approach to iterate the array which is by using the forEach method. This method is different from the traditional approach as it uses a functional approach. This approach provides us with new ways to access each element of the array as well as the whole array. Since we use a functional approach therefore we can also use arrow function syntax with this method.
Syntax:
arr.forEach(function(val, index, wholeArr)){ ... }
Let us look at some examples to iterate through the array using the above approach.
Example 1: In this example, we will iterate t
Javascript
var arr = [2,4,7,8,1] arr.forEach( function (val){ console.log(val) }) |
Output:
2 4 7 8 1
Example 2: In this example, we will iterate through the array using the arrow function
Javascript
var arr = [2,4,7,8,1] arr.forEach((val, index)=>{console.log(`val=${val} index=${index} `)}) |
Output:
val=2 index=0 val=4 index=1 val=7 index=2 val=8 index=3 val=1 index=4
Example 3: In this example, we will access the whole array with the third optional parameter
Javascript
var arr = [2,4,7,8] arr.forEach((val, index, wholeArr)=>{console.log(wholeArr)}) |
Output:
(4) [2, 4, 7, 8] (4) [2, 4, 7, 8] (4) [2, 4, 7, 8] (4) [2, 4, 7, 8]