Day 1: The forEach
Helper
The forEach
helper function can be seen as an alternative to the regular for loop. The forEach()
method basically calls a function (called iterator function
) once for each element in the array, in order.
In simple language, the forEach method loops through each element in an array and runs a function on that particular element.
Example
// Iteration through array
var fruits = [ 'mango', 'orange', 'pineapple', 'guava' ];
// Baisc Syntax
for (var i=0; i<fruits.length; i++) {
console.log (fruits[i]);
}
// forEach syntax
fruits.forEach (function (fruit) {
console.log (fruit);
});
// forEach with arrow function
fruits.forEach (fruit => {
console.log (fruit);
})
Another Example
Find the sum of each element in an array of numbers.
/* ================================================= */
/* ================ Daily JS - Day 1 =============== */
/* ===== Helper Functions - The forEach helper ===== */
/* ================================================= */
/**
* Sum of each element in array of numbers
* 1. Create an array of numbers
* 2. Create a variable to hold the sum
* 3. Loop over the array and increment the sum value
* 4. print the sum variable
*/
const numbers = [6, 1, 2, 3, 8];
let sum = 0;
numbers.forEach (number => {
sum += number;
});
console.log (sum);
Syntax
array.forEach(function(currentValue, index, arr), thisValue)
- currentValue: Required. The value of the current element
- index: Optional. The array index of the current element
- arr: Optional. The array object the current element belongs to
- thisValue: Optional. A value to be passed to the function to be used as its “this” value.
Why forEach?
- Less Amount of Code
- More Readable
- Less Chances of error
Practise questions
[Feel free to add more and open a Pull Request]
1) Find and print product of all numbers in the given array which are divisible by 2?
Download your free eBook
Further Read
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach