In this article, you will learn about the javascript Array built-in method Array.prototype.forEach()
. How does this method work in javascript?
This Array.prototype.forEach()
method invokes a function for each element in the calling array. And it returns undefined
.
array.forEach(callback(element [, index [, array]]) [,thisParameter]);
This method takes 2 parameters as given below:
this
to be used while executing the callback function.The forEach()
does not change the original array. And it executes a callback once for each array element in order.
The forEach()
does not execute the callback function for array empty elements.
Here are some examples of Array.prototype.forEach() method:
const arr = [1, 2, 3, , 5, 10, 8]
//Callback function which prints index and elements
function printElements(element, index) {
console.log('Array Element ' + index + ': ' + element);
}
//foreach() Method
arr.forEach(printElements);
/*
---------------------------------
Output
---------------------------------
"Array Element 0: 1"
"Array Element 1: 2"
"Array Element 2: 3"
"Array Element 4: 5"
"Array Element 5: 10"
"Array Element 6: 8"
*/
Note: There is no way to stop or break a forEach()
loop other than by throwing an exception. If you need such behavior, the forEach()
method is the wrong tool.
The forEach()
method expects a synchronous function. And forEach()
method does not wait for promises.
I hope this article will help you to understand the javascript Array built-in method Array.prototype.forEach().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments