For Each Javascript

For Each Javascript

In this tutorial, you will learn about JavaScript forEach() method with the help of examples.

What is Javascript forEach?

In general, when you need to perform a function on each element of an array, you employ loop statements like this:

let name = ['Tom', 'Brad', 'Neil'];
for (let i = 0; i < name.length; i++) {
    console.log(name[i]);
}

But the forEach() method in JavaScript Array enables you to execute the same function on each element without using the loops. See code below:

let ranks = ['Tom', 'Brad', 'Neil'];

ranks.forEach(function (e) {
    console.log(e);
});

So in Javascript, forEach() method is used to iterate over the elements of an array and call a function for each of the array elements.

If the array element is empty, forEach method will not execute.

The forEach() method is an ECMAScript5 (ES5) feature that is designed to support all browsers.

Syntax of JavaScript forEach() method:

array.forEach(function(currentValue, index, array) {
  // code to be executed for each element
});

The currentValue parameter represents the value of the current element being processed, the index parameter represents the index of the current element being processed, and the array parameter represents the array that forEach is being applied to.

Let’s understand forEach method of Javascript by examples:

<script>

var a = ['Tom', 'Brad', 'Neil', 'Tyson'];
a.forEach(function(value){
  document.write(value + "<br>");
});

</script>
<script>

var a = ['Tom', 'Brad', 'Neil', 'Tyson'];
a.forEach(function(value, index){
  document.write(index + ":" + value + "<br>");
});

</script>

In both the above examples, you can see the javascript foreach method is returning the contents of the array. Note that we can also do the same thing using loops but loops are comparatively memory heavy than this method.

Some more examples of Javascript foreach

Addition of elements of the array using foreach

<script>

let sum = 0;
const numbers = [10, 15, 25, 30];
numbers.forEach(function(item){
   sum += item;
});
document.write(sum)

</script>

Multiplying each element of the array by a number using foreach

<script>

const numbers = [10, 40, 50, 70];
numbers.forEach(function(item, index, arr){
   arr[index] = item * 10;
   
});
document.write(numbers)

</script>

Description of forEach method

The forEach() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order. Unlike map(), forEach() always returns undefined and is not chainable.

forEach() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn.

Read more about these.

  • callbackFn will not visit any elements added beyond the array’s initial length when the call to forEach() began.
  • Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
  • If an existing, yet-unvisited element of the array is changed by callbackFn, its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are not visited.

Why use For Each method in Javascript?

1.) Iterating over arrays: forEach() method is commonly used to loop over arrays and perform a task for each element in the array. For example, you might want to iterate over an array of numbers and performs certain tasks like adding all the numbers. We have seen this in the above example.

2.) Manipulating arrays: forEach() can also be used to manipulate an array by modifying its elements or adding new ones. For example, you might use it for multiplying all the elements of the array by a certain number as we have seen this in the above example.

3.) Asynchronous operations: forEach() method can also be used with asynchronous operations, such as making HTTP requests or reading from a file. However, forEach() does not wait for each operation to complete before moving on to the next element in the array. For this reason, forEach() may not be the best choice for complex asynchronous tasks.

Below is the code for Asynchronous operation:

let urls = ['https://codespit.com', 'https://python.org'];

urls.forEach(function(url) {
  fetch(url).then(function(response) {
    console.log(response);
  });
});

Javascript for each li in ul

To loop through all the li elements in an unordered list ( ul ) using the forEach() method in JavaScript, you can first select the ul element using the querySelector() or getElementById() method, and then call the forEach() method on its children property.

Here’s an example code:

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<script>
const myList = document.getElementById('myList');
myList.children.forEach(function(li) {
  console.log(li.textContent);
});
</script>

In this example, we first select the ul element with an id of myList using the getElementById() method. Then, we call the forEach() method on the children property of the ul element to loop over all the li elements.

For each li element, we log its textContent property to the console. You can replace the console.log(li.textContent) line with any action you want to perform on each li element.