How to use forEach() Method In Javascript

The forEach() Method calls the provided function once for every array element in the order. 

Example: In this example we are using forEach() method for iteration of an array.

javascript
let index = 0;
let array = [1, 2, 3, 4, 5, 6];

array.forEach(myFunction);

function myFunction(item, index) {
    console.log(item);
}

Output
1
2
3
4
5
6

Iterate over an array in JavaScript

Iterating over arrays in JavaScript is a fundamental task that developers frequently perform. JavaScript provides several methods to iterate through arrays, including for, forEach(), map(), filter(), reduce(), and for…of. Each method has its specific use cases, benefits, and best practices. This guide explores these different array iteration methods, demonstrating how to effectively loop through arrays to manipulate and access their elements in JavaScript.

There are many ways to iterate through an array in JavaScript:

Table of Content

  • 1. Using console.log() Method
  • 2. Using for Loop
  • 3. Using while loop
  • 4. Using forEach() Method
  • 5. Using every() Method
  • 6. Using map() Method
  • 7. Using filter() Method
  • 8. Using reduce() Method
  • 9. Using some() Method
  • 10. Using entries() Method

Similar Reads

1. Using console.log() Method

Example: In this example, we will access simple array elements using their index number....

2. Using for Loop

The for Loop executes a set of instructions repeatedly until the given condition becomes false. It is similar to loops in other languages like C/C++, Java, etc....

3. Using while loop

A while loop in JavaScript is a control flow statement that allows the code to be executed repeatedly based on the given boolean condition....

4. Using forEach() Method

The forEach() Method calls the provided function once for every array element in the order....

5. Using every() Method

The every() Method checks if all elements in an array pass a test (provided as a function)....

6. Using map() Method

A map() Method applies a function over every element and then returns the new array....

7. Using filter() Method

filter() Method is used to filter values from an array and return the new filtered array....

8. Using reduce() Method

reduce() Method is used to reduce the array into one single value using some functional logic....

9. Using some() Method

some() Method is used to check whether some array values pass a test....

10. Using entries() Method

The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array. This can be used to access both the index and the value of each element....