forEach: A JavaScript iterator

forEach: A JavaScript iterator

If you are just getting familiar with javascript higher-order functions, you might get confused with maps, for each, filter and reduce.

This is a continuous series that will explain the four concepts broadly and also differentiate them so you know which to use per time.

In this first part of the series, we will learn about forEach in javascript

One major thing to note about forEach is that it always returns undefined. forEach is a javascript iterator so it also is Map and filter. Iterators are Javascript built-in methods on arrays that can be used in place or for loops. However, the issue is picking the right iterator per time.

forEach uses a callback function for its operations and executes the function once for each provided element. It does not return an array, unlike map.forEach loops through an array, executes the callback function but returns the values in the array. Whether you use the return keyword in a forEach iterator or not, does not make a difference. It always returns undefined. The callback function can have up to three parameters. The first is the value at the current array’s index, the second is the current array index and the third is the array itself.

Let’s look at a few examples:

Given an array of five elements in ascending order, print the different values in the array.

Let arr= [1,2,3,4,5];

arr.forEach(function(val,index,arr){

console.log(val)

Answer in the console:

1

2

3

4

5

If you decide to console.log the index
console.log(index),

Answer in the console:
0

1

2

3

4

Here, the val represents the value of the array, the index represents the index of the array, and the arr represents the array itself.

Also, you do not necessarily need to use the three parameters in the forEach callback function. You can use one parameter, two parameters or three parameters. The result remains the same.

Example:
Let arr = [1,2,3,4]

arr.forEach(function(val){

console.log(val)

Answer in the console:
1

2

3

4

Let us see another example:
Write a function that returns a new array with all its values increased by ten.

Function increasedByTen(ten) {

Let increasedArray = [];

ten.forEach(function(val){

increasedArray.push(val + 10);

})

return increasedArray;

If the value of ten = [2,4,6,8,10]

increasedArray = [12,14,16,18,20].

Here, the reason we used the push function is that forEach does not return an array. Instead, it returns undefined.

This is one of the differences between map and forEach.

If you use a map for this, you would write shorter code as your map creates a new array. So you add ten to each value in the new array and it returns a new array.

My Twitter Handle: https://twitter.com/mchelleOkonicha

My LinkedIn Handle: https://www.linkedin.com/in/buchi-michelle-okonicha-0a3b2b194/