JavaScript For Each Loop

The forEach loop in JavaScript is a method used to execute a provided function once for each array element. It offers a more concise way to iterate over arrays compared to traditional for loops and is commonly used for array manipulation.

1. Syntax of forEach Loop:

array.forEach(function(element, index, array) {
    // Code to execute for each element
});

Try It Now

Parameters:

  • element: The current element being processed in the array.
  • index (optional): The index of the current element.
  • array (optional): The array forEach is called upon.

2. Basic Example of forEach:

let fruits = ["Apple", "Banana", "Cherry"];

fruits.forEach(function(fruit) {
    console.log(fruit);
});

Try It Now

Output:

Apple
Banana
Cherry

Try It Now

3. Using forEach with Arrow Function:

let fruits = ["Apple", "Banana", "Cherry"];

fruits.forEach(fruit => console.log(fruit));

Try It Now

Explanation:

  • The forEach loop can be simplified using an arrow function for concise syntax.

Output:

Apple
Banana
Cherry

Try It Now

4. Accessing Index in forEach:

let fruits = ["Apple", "Banana", "Cherry"];

fruits.forEach(function(fruit, index) {
    console.log(`Index: ${index}, Fruit: ${fruit}`);
});

Try It Now

Output:

Index: 0, Fruit: Apple
Index: 1, Fruit: Banana
Index: 2, Fruit: Cherry

Try It Now

5. Modifying Array Elements (with Caution):

let numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number, index, array) {
    array[index] = number * 2;
});

console.log(numbers);

Try It Now

Output:

[2, 4, 6, 8, 10]

Try It Now

Explanation:

  • You can modify array elements directly within the forEach loop, though it’s often better to use methods like map for transformations.

6. forEach vs. for Loop:

  • forEach is easier to read and write, especially for simple array iteration.
  • for loop provides more control over the iteration process, such as breaking out of the loop with break or skipping iterations with continue, which forEach does not support.

7. Using forEach with Objects (Indirectly):

While forEach is designed for arrays, you can use it with objects by converting the object’s properties into an array:

let person = {
    name: "John",
    age: 30,
    city: "New York"
};

Object.keys(person).forEach(function(key) {
    console.log(`${key}: ${person[key]}`);
});

Try It Now

Output:

name: John
age: 30
city: New York

Try It Now

Conclusion:

  • The forEach loop is an excellent tool for iterating over arrays, offering a clean and readable syntax.
  • It’s ideal for performing actions on each element but is not suitable for breaking out of the loop or skipping elements.
  • For transformations or when you need to create a new array based on an existing one, consider using methods like map instead.