Loop Methods

JavaScript Arrays come with some built-in loop methods.

For example; map, filter, reduce, forEach


The advantages of these methods are no side-effects, and clear syntax.

Common for them is that they take a callback function as a parameter.

This can either be as a function reference or an arrow function

forEach

forEach as mentioned above has no side effects, which means it does not mutate the array.

It does not return anything either.

JS

Copy

const numbers = [1, 2, 3];

const forEach = numbers.forEach((element) => console.log(element));

console.log(forEach); // undefined

//output
// 1
// 2
// 3
// undefined

the callback function has 3 parameters that can be passed to it

element, index, array

JS

Copy

const numbers = [1, 2, 3];

numbers.forEach((item,index,array) => console.log(item,index,array));

// output
// 1 0 [ 1, 2, 3 ]
// 2 1 [ 1, 2, 3 ]
// 3 2 [ 1, 2, 3 ]

map

map has no side effects, and returns a new array with mapped values

map takes each value from the original array and maps it to a new value, based on the passed callback function

JS

Copy

const numbers = [1, 2, 3];

const doubledNumbers = numbers.map((number) => number*2 );

console.log(numbers);        // [ 1, 2, 3 ]
console.log(doubledNumbers); // [ 2, 4, 6 ]

As one can see above, the original array is untouched, and the new array contains doubled values!

map's callback function can also take the 3 parameters; element, index, array

filter

Filter has no side effects, and returns a new filtered array

filter takes a callback function that should evaluate to true or false, as a parameter

If it evaluates to true, the element is added to the new array, otherwise it's filtered out

JS

Copy

const numbers = [1, 2, 3, 4, 5, 6, 7, 8];

const evenNumbers = numbers.filter((number) => number % 2 === 0);

console.log(evenNumbers); // [ 2, 4, 6, 8 ]

filter's callback function can also take the 3 parameters; element, index, array

reduce

reduce has no side effects, but is a bit special as it reduces the array to a new single value.

It does this by taking a callback function, which can be called a reducer.


The reducer function takes the parameters previousValue and currentValue.

previousValue is often called the 'accumulator', since it accumulates to a single value at the end.

reduce also takes a second parameter the initialValue

JS

Copy

const numbers = [5,5,5,5];

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // 20

As one can see above, ie takes each value of the numbers array, and adds it to the accumulator.

The accumulator is then passed on to the next element, which is then added to it, and so on.

Until finally we have a single value.