Objects - JavaScript forEach Array
Posted by Superadmin on May 01 2023 04:25:05

JavaScript forEach Array

JavaScript forEach Array

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,

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:

JavaScript forEach Array output 1

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:

JavaScript forEach Array output 2

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:

JavaScript forEach Array output 3

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:

output 4

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:

output 5

We have seen how this forEach() method is used, but let us also know when to use the forEach() method.

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:

output 6

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:

output 7

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.