Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 32 - JavaScript Array Methods – forEach()

The forEach() method in JavaScript provides an elegant way to iterate/traverse over array elements without using traditional loops.


Explanation

  • forEach() executes a provided function once for each array element.
  • It simplifies the process of iterating over arrays.

Syntax:

array.forEach(function(currentValue, index, array) {
  // code to execute
});
  • currentValue: The current element being processed.
  • index (optional): The index of the current element.
  • array (optional): The array forEach was called upon.

Example 1: Basic forEach() Usage

let fruits = ['Apple', 'Banana', 'Mango'];

fruits.forEach(function(fruit) {
  console.log(fruit);
});
// Output:
// Apple
// Banana
// Mango
  • Iterates over the array and logs each fruit.

Example 2: Using Index with forEach()

let colors = ['Red', 'Green', 'Blue'];

colors.forEach(function(color, index) {
  console.log(index + ": " + color);
});
// Output:
// 0: Red
// 1: Green
// 2: Blue
  • Demonstrates how to use the index parameter.

Example 3: Arrow Functions with forEach()

let numbers = [10, 20, 30, 40];

numbers.forEach((num, idx) => console.log(`Index ${idx}: ${num}`));
// Output:
// Index 0: 10
// Index 1: 20
// Index 2: 30
// Index 3: 40
  • Shows how to use arrow functions with forEach().

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson32-foreach.html.
  2. Write the Code:

    • Copy the following code:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 32 - forEach Method</title>
      </head>
      <body>
      <h2>Grocery List</h2>
      <ul id="groceryList"></ul>
      
      <script>
         let groceries = ['Milk', 'Bread', 'Eggs', 'Cheese'];
      
         let list = document.getElementById("groceryList");
      
         groceries.forEach(function(item) {
             let li = document.createElement("li");
             li.textContent = item;
             list.appendChild(li);
         });
      </script>
      </body>
      </html>
  3. Save the File.

  4. Open it in a Browser to See the Grocery List.


Experiment

  1. Create an array of your favorite movies and display them as a list using forEach().
  2. Add a button to add new movies to the list dynamically.
  3. Explore how forEach() behaves with arrays containing undefined or null values.

Key Takeaways

  • forEach() simplifies iterating over arrays.
  • It does not return a new array (unlike .map()).
  • Arrow functions can make forEach() more concise.