Code Highlights logo

Learn

Iterators

The .forEach() Method

The .forEach() method is a higher-order function that takes a callback function as its argument. It allows us to loop through each element in an array and perform a specific action. This method is commonly used when we want to perform a task on each item in an array without the need for a separate loop.

Syntax

The syntax for the .forEach() method is as follows:

1array.forEach(callbackFunction(currentValue, index, array){
2 // Code to be executed on each element
3});
  • array: The array that the .forEach() method is being applied to.
  • callbackFunction: The function to be executed on each element of the array.
  • currentValue: The value of the current element being processed.
  • index (optional): The index of the current element being processed.
  • array (optional): The array that the .forEach() method is being applied to.

Using the .forEach() Method

Let's see how we can use the .forEach() method in practical examples:

Example 1: Printing each element in an array

1const numbers = [1, 2, 3, 4, 5];
2
3numbers.forEach(function(number) {
4 console.log(number);
5});

Example 2: Manipulating each element in an array

1const names = ['John', 'Jane', 'Robert'];
2
3names.forEach(function(name, index) {
4 names[index] = name.toUpperCase();
5});
6
7console.log(names);

Benefits of the .forEach() Method

  • Simplicity: The .forEach() method offers a concise and readable way to iterate over arrays.
  • Performance: The .forEach() method is optimized for performance and often outperforms traditional for loops.
  • Closures: The callback function used in .forEach() allows for the use of closures, providing scope for variables within the loop.

Instructions

1.

In the provided code, there is a numbers array containing some numbers. Your task is to use the .forEach() method to iterate over each number in the array and console.log it.
Replace the comment (// TODO: Use the .forEach() method to console.log each number in the array) with your solution.

Sign up to start coding

Already have an account?

Sign In

Course content