JavaScript forEach () is a method or function which calls the provided function for each element in an array in order. It is used to perform any operation on elements of the given array. Remember, it can not be executed for array elements without values.
Table of Contents
JavaScript ForEach () Supported Browsers
The following browsers support JavaScript ForEach () method:
- Google Chrome
- Internet Explorer v9.0 or above
- Mozilla Firefox v1.5 or above
- Safari
- Opera
JavaScript ForEach () Syntax
array.forEach(function(current_Value, index, arra), thisValue)
Where arra is optional parameter which is the current array to whom an element belongs. index is also optional parameter which is index of current element. currentValue is required parameter which is value of current element. thisValue is optional, it will be “undefined” if left empty, a value “this” should be passed.
You may be interested in learning Express JS.
JavaScript ForEach () Technical Details
- JavaScript ForEach () is supported in ECMAScript 5.
- It always returns undefined value by altering or without altering the provided array. Change in the array depends on the functionality of the argument function.
JavaScript ForEach () Examples
Example 1: Print Colors and associated index.
var colors = ["Blue", "Yellow", "Red"] colors.forEach(myColors); function myColors(color, index){ document.getElementById("myDiv").innerHTML += color + ":"+ index + "<br>"; }
Example 2: Create a copy of array by multiplying each element’s value with 2
var values = [1, 2, 3] var clone = []; values.forEach(myClone); myClone(value){ clone.push(value * 2); } print(clone);
Example 3: Print sum of array elements using JavaScript forEach ()
var sum = 0; var array = [155 , 45, 87, 8, 98, 14, 74]; array.forEach(mySum); function mySum(num){ sum += num; console.log(sum) }
Sponsored by WebSoft IT Development Solutions Private Limited