Skip to main content
javascript-foreach

JavaScript Foreach Example & Demo

This tutorial help to understand JavaScript forEach() method with a working example. You can use this method on Arrays, Maps, and Sets datatype.

It executes a provided function once for each element in the array, allowing you to perform actions or operations on each element individually

The forEach() method executes a provided function once for each array element. You can pass a method/callback or write logic within foreach method. The forEach() does not execute the function for an empty array or without an elements array.

However, it’s important to note that the forEach() method does not support breaking or skipping iterations like other loop constructs for or while loops.

JavaScript Foreach Method with Example

In this article, we will explore an example and provide a demo of how to use the forEach() method in JavaScript.

The forEach() method syntax as follows –

arr.forEach(function(currentValue, index, array) {
    //your iterator
});
  • currentValue : Required params for forEach() method.The value of the current element.
  • index – Optional params for forEach() method. The array index of the current element.
  • array – Optional params for forEach() method. The array object the current element belongs to.

JavaScript forEach() working Demo

We will create a simple array and iterate on each element of an array using foreach() method, We will print each element of the array.

var numArr = [1, 2, 3];

numArr.forEach(function(element) {
  console.log(element);
});

In this above, We have an array called numArr that contains a series of numbers. We use the forEach() method to iterate over each element in the array. The provided function takes each element as an argument and logs it to the console.

Output – 1 2 3

JavaScript forEach() With Callback Method

We will create a printLog() method and passed this method into foreach method as a callback. We will print each element of an array.

var numArr = [1, 2, 3];

numArr.forEach(printLog);

function printLog(item) {
  console.log(element);
}

Output – 1 2 3

You can also call foreach method into onclick event of button or any element click event –
onclick="numArr.forEach(printLog)"

JavaScript For Loop

You can access same results using for loop. We can iterate on object array using for loop and perform operation.

const numArr = [1, 2, 3];

for(let i = 0; i < numArr.length; i++) {
  console.log(numArr[i]);
}

Both the for loop and the forEach method allow us to loop over an array element but foreach is better than forloop as on a performance scale.

Demo:

To see the forEach() method in action, you can try running the following code snippet in your browser’s JavaScript console or by embedding it in an HTML file:

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript Foreach Demo</title>
  </head>
  <body>
    <script>
      const colors = ["red", "green", "blue"];

      colors.forEach(function(color) {
        document.write(`<p>${color}</p>`);
      });
    </script>
  </body>
</html>

in the above code, We have an array called colors. We use the forEach() method to iterate over each element in the array and displayed as separate paragraphs on the HTML body using document.write().

Conclusions:

The forEach() method in JavaScript is a powerful tool for iterating over arrays and array-like objects. It allows you to easily perform actions on each element individually without the need for traditional loop structures.

Leave a Reply

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