Loop (for each) over an array in JavaScript

Master the art of iterating over arrays in JavaScript using the forEach loop. Dive into the syntax, examples, and discover best practices for efficient array iteration.

Syntax

The forEach loop is a concise and powerful way to iterate over elements in an array. Here's the basic syntax:


        array.forEach(function(element, index, array) {
            // Your code here
        });
    

The callback function receives the current element, its index, and the entire array as parameters.

Best Answer

The forEach loop is the best choice when you want a clean and readable way to iterate over array elements without the need for manual indexing.

All Scenarios and Use Cases

The forEach loop is versatile and can be used in various scenarios. Some common use cases include:

Examples with Answers

Let's explore practical examples of using the forEach loop:


        // Example 1: Logging each element to the console
        const fruits = ['apple', 'banana', 'orange'];
        fruits.forEach(function(fruit) {
            console.log(fruit);
        });
        // Output: apple, banana, orange
    

Exercises with Answers

Test your knowledge with the following exercises:

  1. Write a forEach loop to double each element of the array [1, 2, 3].
  2. Your Answer: [Your code here]

  3. Create a new array that includes only the even numbers from [1, 2, 3, 4, 5].
  4. Your Answer: [Your code here]

Questions & Answers

Explore common questions related to forEach loops:

Question 1: Can I use the forEach loop on an empty array?

Answer: Yes, forEach won't execute the callback if the array is empty.

Question 2: Does the forEach loop modify the original array?

Answer: No, forEach does not modify the array it is iterating over.

Best Practices and Examples

Follow these best practices for effective array iteration:


        // Best Practice Example: Using arrow function
        const numbers = [1, 2, 3];
        numbers.forEach(number => console.log(number * 2));
        // Output: 2, 4, 6
    

Alternatives

While forEach is a powerful tool for array iteration, there are alternative methods you might consider based on specific needs:

Multiple Choice Questions (MCQ)

  1. What is the purpose of the forEach loop in JavaScript?
  2. Your Answer: [Your choice]

Quizzes

Test your knowledge with the following quizzes:

  1. What is the output of the following code?
  2. 
                const numbers = [1, 2, 3];
                numbers.forEach(number => console.log(number * 2));
            

    Your Answer: [Your choice]

Advanced Examples

Explore advanced use cases of the forEach loop in JavaScript:


        // Advanced Example: Modifying the original array
        const prices = [10, 20, 30];
        prices.forEach((price, index, array) => {
            array[index] = price + 5;
        });
        console.log(prices);
        // Output: [15, 25, 35]
    

Notes

Here are some important notes to keep in mind when using the forEach loop:

Most Asked Questions with Answers

Explore some of the most commonly asked questions related to array iteration in JavaScript:

Question: Can I use forEach on an object?

Answer: No, forEach is specifically designed for arrays.

Summaries

Summarize your learning on looping over arrays using forEach in JavaScript:

Summary 1: forEach provides a concise and readable way to iterate over array elements, but alternatives may be more suitable for certain scenarios.

Here's how to loop over an array in JavaScript using the for...of loop:

Syntax:

JavaScript
for (const element of array) {
  // Code to execute for each element
}

Explanation:

  1. for: Initiates the loop.
  2. const element of array:
    • Declares a constant variable element to hold the current element in each iteration.
    • of array specifies the array to loop over.
  3. // Code to execute for each element: The code within this block runs for each element in the array.

Example:

JavaScript
const numbers = [1, 2, 3, 4, 5];

for (const number of numbers) {
  console.log(number); // Output: 1, 2, 3, 4, 5
}

Key Points:

Alternative: Traditional for Loop:

JavaScript
for (let i = 0; i < array.length; i++) {
  const element = array[i];
  // Code to execute for each element
}

Choose for...of for:

Choose traditional for loop for: