Thursday, October 23, 2025
HomeLanguagesJavascriptHow to iterate an Array using forEach Loop in JavaScript?

How to iterate an Array using forEach Loop in JavaScript?

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]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS