Introduction to JavaScript forEach Array
JavaScript forEach Array is used to iterate an array in JavaScript. forEach method iterates in ascending order without modifying the array. JavaScript forEach method works only on arrays. If there are no elements in an array, the forEach method won’t be executed. If existing elements of the array are changed or deleted, the value which is passed to callback will be the values passed for the forEach method. Let us see how JavaScript forEach method works, its syntax with some illustrations to make you understand better.
Syntax
sampleArray.forEach(function, (currentValue, index, array), thisValue);
So here, the parameters are described below,
- sampleArray: It is the array on which the forEach method is called.
- forEach: It is the method called on an array with the other parameters.
- function, (currentValue, index, array): function with 3 parameters is required to run each element of the array
- currentValue: This is the value of the current element.
- index: This is the index of the element which is to be processed.
- array: This is the array object on which function is to be called.
- thisValue: It is the value to be used as a function’s ‘this’ value on executing it. If ‘this’ value is not provided, ‘undefined’ is passed.
Here, index, array, and thisValue are optional parameters.
Examples of JavaScript forEach Array
We shall see how this forEach method is used in actual programming with examples.
Example #1
Code:
<!DOCTYPE html>
<html>
<body>
<p>Listing all the array items using forEach method</p>
<p id="demo"></p>
<script>
var veggies = ["Potato", "Spinach", "Capsicum"];
veggies.forEach(sampleFunc);
function sampleFunc(itemName, index) {
document.getElementById("demo").innerHTML += index + ":" + itemName + "<br>";
}
</script>
</body>
</html>
Output:
Example #2
Code:
<!DOCTYPE html>
<html>
<body>
<p>Multiplication of each array item with itself by iterating the array using forEach</p>
<p id="demo"></p>
<script>
const numbers = [23, 3, 43, 4, 78, 8];
const square = [];
numbers.forEach(function(num){
square.push(num*num);
});
document.write(square);
</script>
</body>
</html>
Output:
Example #3
Code:
<!DOCTYPE html>
<html>
<body>
<p>Accessing the index item for each element in array using forEach method</p>
<p id="demo"></p>
<script>
const employeeNames = ['Karthick', 'Jack', 'June'];
function iterateFunc(item, index) {
document.write(`${item} has index ${index}` + "<br/>");
}
employeeNames.forEach(iterateFunc);
</script>
</body>
</html>
Output:
Example #4
forEach() method accepts a synchronous function and does not wait for promises.
Code:
<!DOCTYPE html>
<html>
<body>
<p>Addition of two numbers by iterating array using forEach method</p>
<p id="demo"></p>
<script>
let numbers = [50, 14, 25];
let sumNum = 0;
let sumFunction = async function (a, b, c)
{
return a + b + c
}
numbers.forEach(async function(x) {
sumNum = await sumFunction(sumNum, x)
})
document.write(sumNum)
</script>
</body>
</html>
Output:
forEach() method calls provided function for each array element in order. and items are used to store current value, and results of all elements of the array are displayed on the console.
Example #5
Code:
<!DOCTYPE html>
<html>
<body>
<p>Using forEach() method to find the index of the item</p>
<p id="demo"></p>
<script>
var array = ["Karthick","Sandeep","Honey","Jack"];
array.forEach(function(item,index,arr) {
document.write("item: " + item + " at index: " + index + " in the array: " + arr + " <br/> ");
})
</script>
</body>
</html>
Output:
We have seen how this forEach() method is used, but let us also know when to use the forEach() method.
- forEach() is used to iterate array items without having any side effects.
- Some of the side effects are outer scope variable, DOM manipulations, I/O operations, etc.
- In the callback function, the value of the input field is cleared.
- Normally, iteration of forEach() cannot be broken, to break this chain, we need to use some other array method like an array.map(), array.every(), array.some() or array.reduce().
Example #6
Code:
<!DOCTYPE html>
<html>
<body>
<p>Using forEach() method to detect if all numbers in array are even</p>
<p id="demo"></p>
<script>
let allEven = true;
const numbers = [22, 32, 42, 10];
numbers.forEach(function(number) {
if (number % 2 === 1) {
allEven = false;
}
});
document.write(allEven);
</script>
</body>
</html>
Output:
This code above determines if all the numbers in the array are even or nor with a Boolean value ‘true’ or ‘false’. If we want to break the forEach() for array [4, 7, 9,6] at odd number 7, use array.every() so that iteration would break after finding an odd number immediately instead of iterating the complete array and then giving out the result.
Example #7
Code:
<!DOCTYPE html>
<html>
<body>
<p>Using forEach() method for programming a Counter</p>
<p id="demo"></p>
<script>
function sampleCounter() {
this.count = 0;
let num = this;
return {
increase: function () {
num.count++;
},
current: function () {
return num.count;
},
reset: function () {
num.count = 0;
}
}
}
var counter = new sampleCounter();
var numbers = [5, 3, 8];
var sumNum = 0;
numbers.forEach(function (e) {
sumNum += e;
this.increase();
}, counter);
document.write("Sum of numbers in array is: ", sumNum + "<br/>");
document.write("counter value: " , counter.current());
</script>
</body>
</html>
Output:
Here we are creating a new Object sampleCounter and defining an array of 3 numbers. Declaring a variable sumNum and assigning 0 as value. Then we call the forEach() method on the array of numbers and add them, increase() method to the object. Hence the final output will be sum of the array and the count of the elements inside the array.
Conclusion
With this, we conclude our topic ‘JavaScript forEach() Array to execute or iterate over an array without breaking or involving any side effects.’ We have seen what is JavaScript forEach() method in Array and its syntax. Have gone through some of the simple examples listed above, which you people can easily understand and explore further on the method forEach(). We have also seen some of the limitations while programming using forEach(). Array.forEach() method is one of the efficient ways to iterate over the array items.