JavaScript foreach loop statement is an advanced version of for loop. Java array forEach method iterates over the array items, in ascending order, without mutating the array.
Syntax
array.forEach(function(currentValue, index, array), thisValue)
Parameter Values
Function is required to be run for each element in the array.
- currentValue:– The current element being processed in the array.
- index:- The array index of the current element. (Optional)
- array:- The array object the current element belongs to
thisArg:- Value to use as this when executing callback.
Example of JavaScript foreach loop
Let’s do example of sum of all the values in the array.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var sum = 0;
var numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
alert(sum)
</script>
</body>
</html>
Output:
How to Javascript foreach string in list(Array)
Example of print index and its value of JS array using foreach loop.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var fruits = ["A", "B", "C"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML += index + " : " + item + "<br>";
}
</script>
</body>
</html>
Output:
Q: How to forEach push to array JavaScript?
Answer: Let’s copy all the values from one array to another array using the Javascript foreach function and Javascript push() function.
<!DOCTYPE html>
<html>
<body>
<script>
const elements = [11, 21, 46];
const copy = [];
elements.forEach(function(element){
copy.push(element);
});
console.log(copy);
</script>
</body>
</html>
Output: [11, 21, 46]
Do comment if you have any questions and suggestions on this tutorial.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version