dailyjs

Master the most awesome language, one concept a day!

View on GitHub

Day 1: The forEach Helper

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.

Solution

/* ================================================= */
/* ================ 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)

Why forEach?

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

Claim Your Free PDF Here

Further Read

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Carbon Code Sample

code

Carbon