For each method in JavaScript is a method for performing operations on each element of an array without having to write a loop.
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]);
}
Brad
Neil
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);
});
Brad
Neil
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>
Brad
Neil
Tyson
<script>
var a = ['Tom', 'Brad', 'Neil', 'Tyson'];
a.forEach(function(value, index){
document.write(index + ":" + value + "<br>");
});
</script>
1: Brad
2: Neil
3: Tyson
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.
- 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.
forEach() method in other programming languages
The forEach()
method exists in several other programming languages besides JavaScript, and it is often used for iterating over lists or arrays.
Here are some examples of other programming languages that have a forEach()
method:
- Java: In Java, the
forEach()
method is available in thejava.util.stream
package and can be used to iterate over collections or arrays. Here’s an example:
Java:
Java
List<String> myList = Arrays.asList("item 1", "item 2", "item 3");
myList.forEach(item -> System.out.println(item));
C#:
In C#, the ForEach()
method is available in the System.Collections.Generic
namespace and can be used to iterate over lists or arrays. Here’s an example:
List<string> myList = new List<string> { "item 1", "item 2", "item 3" };
myList.ForEach(item => Console.WriteLine(item));
Python:
In Python, the forEach()
method is not built-in, but the for
loop can be used to iterate over lists. Here’s an example:
myList = ["item 1", "item 2", "item 3"]
for item in myList:
print(item)
In Javascript, foreach() method is also very helpful in DOM manipulation. For example, if you are trying to target all the classes having the same name in DOM manipulation, by default, it only causes an effect on the first class in the list. But by using foreach method, we can cause an effect on all the classes in the list.
To target all the classes of the same name in DOM manipulation using the forEach
method in JavaScript, you need to select the elements with the desired class name using a DOM selector such as document.getElementsByClassName or document.querySelectorAll.
const elements = document.querySelectorAll('.my-class');
elements.forEach(element => {
element.textContent = 'Hello';
});
These are just a few examples of programming languages that have a forEach()
method or similar functionality for iterating over lists or arrays. The syntax and usage of the forEach()
method may vary depending on the programming language.
Conclusion
The forEach
method is a built-in method in JavaScript that is available on arrays. It allows you to iterate over each element of an array and perform a specified action on each element.
Note that the forEach
method does not return a new array. It simply iterates over each element and performs the specified action. If you need to transform the elements of an array and create a new array based on the transformation, you might consider using the map
method instead.
Related posts
JavaScript Confirm() Method
JavaScript Array slice()
setTimeout Javascript