Node.Js forEach() statement Explained [Practical Examples]

The forEach() method is one of the ways you can enumerate over arrays in JavaScript. This method exists in all JavaScript arrays. forEach() loops are mainly used when you have to manipulate each item in an array.

This article discusses how to implement the forEach() statement and provides practical examples.

Advertisement

 

Understanding the Node.Js forEach() Statement

The forEach() statement receives a callback function which is called for each element in the array. The callback function can receive the following parameters:

  • The current element - This is a required value that indicates the current value in the array.
  • Index - An optional value indicating the index of the current element.
  • Array - An optional array object being traversed.

The forEach statement calls the callback function for each element in the array in ascending order and only once. This method always returns undefined() and does not mutate the array it is iterating over.

 

Examples of Using forEach() Statements

Below are some practical examples of how you can use forEach()

 

Example-1: Copying items from one array to another

You can use the forEach() statement to copy the elements of one array to another. You will first need to declare an empty array, then add each element from the original array to it.

let array1 = [1, 2, 3, 4, 5]
let array2 = [ ]
array1.forEach(element => {
  array2.push(element)
})
console.log(array2)
// Output
// [1, 2, 3, 4, 5]

 

Example-2: Displaying all the items in an array

If you are looking to print all the elements in the array, you need to log each element on the console.

let items = ['item1', 'item2', 'item3', 'item4', 'item5']
items.forEach(item => {
  console.log(item)
})
// Output
// item1
// item2
// item3
// item4 
// item5

 

Example-3: Tracking the index of an element in the array

As mentioned earlier in the article, the callback function of the forEach() statement accepts an optional parameter representing the index of each element in the array.

Advertisement
let array1 = [1, 2, 3, 4, 5]
array1.forEach((element, index) => {
  console.log(`index of ${element} is ${element})
})

 

Example-4: Modifying an element from an array

The callback function passed into the forEach() statement can be used to modify an array. Consider the following code that increments each item in the array by 1.

let array1 = [1, 2, 3, 4, 5]
array1.forEach((element, index) => {
  array1[index] = element +1
})
console.log(array1)
// Output
// [2,3,4,5,6]

 

Example-5: Refactoring the callback function

In the examples above, you are defining the function inside the forEach statement. You could instead choose to define a new function and pass it to the forEach() method as an argument. The following code displays the items in an array.

let array1 = [1, 2, 3, 4, 5]
function displayElement(element) {
  console.log(element)
}
array1.forEach(displayElement)

 

How to Exit a forEach Loop in JavaScript

When using loops, you might need to break out of the loop. Unfortunately, forEach() does not provide a direct way of breaking out of a loop. For instance, if you were searching an array and wanted to exit the loop when you found it, you could think of using the break keyword. However, using 'break' in a forEach() statement doesn’t work and would throw a syntactic error.

Instead, you could use ‘every’ which tests every element against a function and returns either true or false. The loop breaks if false is returned. The code below searches for the number 2 in the array by returning false when it is found.

let arr1 = [1, 2, 3, 4, 5]
arr1.every(element => {
  return !(element === 2)
})

 

Another alternative would be to use the ‘some’ keyword. 'some' works the same way as every only that it exits the loop if the function returns true. You could therefore rewrite the above function as follows:

let arr1 = [1, 2, 3, 4, 5]
arr1.some(element => {
  return (element === 2)
})

 

It is worth mentioning that one of the most common methods used for iteration in JavaScript is the for loop. Consider the code below. It logs each element in an array on the console as a forEach() statement would. 

Advertisement
let arr1 = [1, 2, 3, 4, 5]
for (i = 0; i < arr.length; i++) {
  console.log(arr1[i]);
}

 

When to Use a forEach()statement

While forEach() and the for loop can provide the same output, there are a couple of things you should consider before choosing one of them to use in your code. 

 

If you want to maintain the scope within the block.

Using a forEach() statement allows you to maintain the variable scope within the callback function. Therefore, if you reused a variable declared outside the forEach() statement inside forEach(), that variable would not be affected. In the code below, the console statement in the forEach() block, displays the contents in the array even though the ‘element’ variable name is reused. If you try logging the ‘element’ outside forEach(), you will print 1.

let array1 = [1, 2, 3, 4, 5]
let element = 1
array1.forEach((element) => {
  console.log(element)
})
// Output
// 1
// 2
// 3
// 4 
// 5
console.log(element)
// Output
// 1

 

If you want to write less verbose code

Compared to the for loop, forEach() requires less code to write. You do not have to declare a variable to increment or keep track of the index of the element in the array. Instead, your array calls the forEach() method directly. Due to the compact code, the forEach() statement is easy to read. For instance, if you were to use a for loop to find the common numbers in two arrays, this is how you would go about it.

const arr1 = [1, 2, 3, 4, 5]
const arr1 = [5, 8, 7, 1, 9]
let commonNums = []
function compareArrs (arr1, arr2) {
    for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j]) {
              commonNums.push(arr1[i]);
            }
        }
    }
    console.log(commonNums)
}

With a forEach() method, the above code would look as follows: 

const arr1 = [1, 2, 3, 4, 5]
const arr1 = [5, 8, 7, 1, 9]
let commonNums = []
arr1s.forEach(element => {
    if (arr2.includes(element)) {
        return commonNums.push(element);
    }
});
console.log(commonNums);

 

Next Steps

In this article, you learned how you can use the forEach() to iterate over an iterable in JavaScript. There are other ways you can implement loops in JavaScript including for loops. When iterating over array elements, you should opt for forEach() whereas using map() and reduce() would work well when your function depends on the results from the values in the array.

When choosing a method, start by trying to solve the problem first then refactoring your code to use your preferred method.

Advertisement

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X