Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

When and how to use Javascript forEach method

javascript foreach

The Javascript forEach method exists within all Array, and it inherits from Array.prototype. The forEach() method, iterate through each item of an array and apply a callback function on each item of an array.

The forEach method is a higher-order function, it provides cleaner, shorter, more concise, and easy to understand code. But it is not suitable for all situations. Each loop has pros and cons, we’ll learn when and where to use it.

Javascript forEach method syntax

The forEach() method calls a function for each element in an array by sequential. We can use this built-in array method, forEach(), that provides almost the same functionality as a for/of the loop.

array.forEach(callbackFn)

array.forEach(function(element, index, arr), thisValue)

array.forEach((element) => { })

array.forEach((element, index) => { ... })
array.forEach((element, index, array) => { ... })

Where array, is an array element or array object. As we learned that forEach will look through the array and invoke a callback function on each value. The callback function takes one to three parameters as follows.

Parameter nameDescription
elementThe element represents an individual element of an array at a moment.
indexIt is optional and it represents an index of an item in an array at a moment.
arrThe arr is an optional parameter, it represents the array, on which we invoke forEach method.
Javascript forEach callback function parameter

Javascript forEach example

We had learned about the basic concept about forEach and syntax of forEach method of an array. Let demonstrate a few examples of it.forEach example with all three-parameter of a callback function

Let demonstrate an example of forEach with all three parameters, element, index, and array. Here we used index, Javascript forEach index also.

The output of above forEach we’ll get an individual element, index, and whole array element.

Javascript forEach example

Javascript forEach example with one parameter

In our second example, forEach callback with one parameter only that is an element, both index and an array is optional.

[1, 2, 3, 4, 5, 6, 7].forEach((number) => {
   if (number % 2 == 0) {
       console.log(number, " is even")
   }
});

The output of the above forEach on an array is

2 ' is even'
4 ' is even'
6 ' is even'

forEach example with callback function

Now let add function as a parameter in the forEach method, we can keep this function outside of the forEach() method. Let find the square of all elements of an array.

Javascript forEach callback
We have pass square function as callback in forEach method.

Javascript forEach index

In our first example, we already used Javascript forEach method with index. In our second example, we’ll demonstrate Javascript forEach index in a callback function.

Javascript forEach index

In this example, we had used the index in a callback function and let demonstrate the second example with the same output.

let text = '';
const companies = ['Apple', 'Google', 'Tesla', 'Facebook'];

companies.forEach((element, index) => {
    text += 'Sno ' + (index + 1) + ':' + element + ' at index ' + index + '<br>';
});

document.getElementById('demo').innerHTML = text;

An example is three to start forEach loop at a certain index by using the slice method.

const arrayNum = [2, 3, 4, 5, 6, 8, 10];

function square(item) {
    console.log(item * item);
}

arrayNum.slice(2, 4).forEach(square); //Output: 16 25

arrayNum.slice(2).forEach(square); //Output: 16 25 36 64 100

Javascript forEach break

In Javascript for loop, we can use a break and continue keywords. The break statement allows us to jump out of the loop based on condition. The continue statement allows us to discontinue the current iteration remaining code and jump to the next iteration in the loop.

The forEach is a higher-order function, help us to achieve the abstraction concept, user don’t need to understand the implementation of the loop. The forEach provides us with shorter and readable looping code.

But in forEach when we execute iteration, then there is no way out and we can’t quite in between of iteration using a break statement.

Warning: Using break statement in forEach will show error of this message Uncaught SyntaxError: Illegal break statement

This is the same for javascript foreach continue, using continue statement in forEach will generate an error, as we can’t discontinue or terminate forEach loop in between.

Javascript forEach object

Let demonstrate forEach on the object of an array. Here is our code to display only the name property of countries array objects.

const countries = [
      { id: 1, name: "England" },
      { id: 2, name: "Scotland" },
      { id: 3, name: "Wales" },
      { id: 4, name: "Northern Ireland" },
      { id: 5, name: "Republic of Ireland" },
      { id: 6, name: "France" },
      { id: 7, name: "Germany" }
];

countries.forEach((element, index) => {
       console.log('Country name:' + element.name);
});

The output of Javascript forEach object array of the above example.

Country name:England
Country name:Scotland
Country name:Wales
Country name:Northern Ireland
Country name:Republic of Ireland
Country name:France
Country name:Germany

Difference between Javascript for loop and forEach

Each of these loops has pros and cons, so we can’t say this is the best loop, each of these loops has usage and once we understand its feature, then we can decide when and where to use these loops.

forEachfor Loop
Is a method from an array, that is inherited from Array.prototype and provides the same functionality as for loop.For loop statement used to iterable objects.
We can’t use a break and continue statement, using it will generate an exception error.We can use a break and continue statement.
forEach is used for small code and where we needed to call the callback function on each element of an array, where we don’t need to terminate the array in between.The for loop allow us to use a break and continue, if we have a large array then using break and continue based on your requirement, provides slightly better performance if you used these two keywords. In general, if we don’t want to apply break and continue, then, there is not much difference in performance.
forEach is a higher-order function, it provides cleaner, readable code, and provides block scope for the variable. The forEach doesn’t mutate the array on which it is called, however, the callback may do so.In for loop, there is more chance of getting an error, if we didn’t use it carefully. Using var to declare index in for loop, as var has functional-scope. So always use let to declare index in for loop.
We don’t need indexing and incrementing the value of an index, as we do in for loop.In for loop, we need to add index and increment index values.

Javascript forEach vs map

We’ll learn the difference between Javascript map vs forEach. Both map and forEach are higher-order functions, both of them have different usage. The map is a method and not a loop.

  1. The forEach has no return value and it return undefined, both map and filter method return new array with the results of calling a provided function on every element in the calling.
  2. The forEach doesn’t wait for promise, it only dealing with synchronous code and doesn’t under aysnc and await.

Related posts

When and how to use Javascript forEach method

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top