Updated April 1, 2023
Introduction to JavaScript forEach()
JavaScript forEach() is related to the execution of a function on each element of an array which means that for each() method is exclusively related to the elements defined in an array. This can only be used on Maps, Arrays and sets which represents another fact that the elements should be arranged in a specific order to perform some activity. Whenever a for each() method is executed it is associated with callback function which will be executed on each element present in the ordered data structure like Maps, Arrays and Sets.
Syntax
Ordered data structure(callback function() (present_value [,index[,data_structure]])[, thisArg])
arr.forEach(callback(present_value [, index [, array]])[, thisArg])
map.forEach(callback(present_value [, index [, map]])[, thisArg])
Explanation:
- callback – callback here represents the most important function to execute on each element of the data structure at the time of calling forEach method.
- present_value – present value here refers to the current element to be processed in the array of elements.
- Index – represents the current value in the array.
- data_structure – data_structure here represents the data structure like array, map or sets kind of ordered data structure to be used for easy traversals and accessing of elements.
- thisArg – it represents the parameter to be used while executing the callback function while using this argument at the time of passing the parameter.
The return type forEach() function is undefined.
How forEach() method works in JavaScript?
forEach() method in JavaScript is mostly associated with some type of ordered data structures like array, maps and sets. Therefore, its working depends on the call of forEach() method with callback function. Call back function further depends on the call of forEach method once it is called for each element in an array in some ascending order. It never gets a call for some undefined, uninitialized or deleted index properties.
Further the callback function is invoked with three parameters:
- The present value of the element to be accessed
- The index of the element defined in an ordered data structure like arrays, maps or sets.
- Traversal of the object present in the data structure like arrays, maps or sets.
Now , in case a thisArg parameter is decided to be passed within the data structure so defined then it will be used as callback’s this function. Behavior of thisArg is like other this as seen by other functions of the method. Also, it is ultimately observable by callback which is determined by this value respectively. The range of elements defined within the data structure is decided and fixed before processing by forEach() method and then it will be used as callback of this function. Therefore, Elements which will be defined and fixed after the calling of forEach() method will not be called or visited by the callback function for invocation.
If in case the elements are deleted once the callback makes a parse which means if any deletion is done after traversal on the element after the callback function is called, then that value will be passed to the forEach() function for its use. One more case suppose the elements that are already visited are removed during the iteration and traversal then the later elements will be skipped which is planning to execute the callback function further.
Unlike map data structure forEach() method do not have any return type and it does not have the ability to reduce and stop the functionality of the array. forEach() method does not replicate and multiply the array on which it is called but if the desire is to stop or break the loop of forEach() method then it is a wrong choice made. forEach() method always expects a synchronous function and implication of using an asynchronous function is very bad and can lead to bad output.
Examples to implement forEach() in JavaScript
Below are the examples:
Example #1
This Program is written to get the sum of all the values in the array using forEach() method in JavaScript.
Code:
<!DOCTYPE html>
<html>
<body>
<p> Sum of numbers in the array.</p>
<p id="demo1"></p>
<script>
var sumno = 0;
var numbr = [20, 40, 10, 6];
numbr.forEach(Funct1);
function Funct1(item) {
sumno += item;
document.getElementById("demo1").innerHTML = sumno;
}
</script>
</body>
</html>
Output:
Example #2
This Program is written for each element in the array to update the value with eight times the actual value.
Code:
<!DOCTYPE html>
<html>
<body>
<p> Consider each element in the array and multiply the value with 8 after that update the value:</p>
<p id="demo3"></p>
<script>
var numbr = [80, 22, 18, 6];
numbr.forEach(Function3)
function Function3(element, index, arr) {
arr[index] = element * 8;
}
document.getElementById("demo3").innerHTML = numbr;
</script>
</body>
</html>
Output:
Example #3
This program is used to illustrate the substring function within the elements using forEach() method of JavaScript.
Code:
<!DOCTYPE html>
<html>
<body>
<p> To represent the substring function using forEach() function </p>
<script>
function func2() {
const items = [10, 28, 15];
const copy = [];
items.forEach(function(item1){
copy.push(item1*item1);
});
document.write(copy);
}
func2();
</script>
</body>
</html>
Output:
Example #4
This program is used to get some typed array using call back and forEach() method respectively for printing all the typed arrays in one go.
Code:
<!DOCTYPE html>
<html>
<body>
<p> To represent the typed array forEach() function </p>
<script>
const P = new Uint8Array([ 5, 4, 9, 0 ])
const Q = new Uint8Array([ 3, 7, 5, 8 ])
function callback(elmnt, index, array) {
document.write('a[' + index + '] = ' + elmnt + "<br>");
}
P.forEach(callback);
Q.forEach(callback);
</script>
</body>
</html>
Output:
Conclusion
forEach() method is used with reference to the Array references segment and is mostly used with callback function and synchronization of the elements while accessing and retrieving the elements in a sorted manner for further utilization therefore not at all suitable for the elements arranged in an asynchronous manner.
Recommended Articles
This is a guide to JavaScript forEach(). Here we discuss the introduction to JavaScript forEach(), Syntax, how does it works, examples with codes and outputs. You can also go through our other related articles to learn more –