Higher Order Functions

  • Value, index and array are the three parameters. ForEach
let arr = [4,6,7,9,2];

arr.forEach((value, index, arr) => {
  console.log(value, index, arr)
})

/***
// Output
4 0 [ 4, 6, 7, 9, 2 ]
6 1 [ 4, 6, 7, 9, 2 ]
7 2 [ 4, 6, 7, 9, 2 ]
9 3 [ 4, 6, 7, 9, 2 ]
2 4 [ 4, 6, 7, 9, 2 ]

***/


  • forEach does not have break or return.
  • forEach does not return anything.
  • You cannot chain any other method after forEach since it does not return anything.

Map

  • map also does not have break or return.
  • map does return a new array. It does not modify the original array.
  • Since this return another array you can chain forEach or some other method to it
let arr = [4, 6, 7, 9, 2];

const newArr = arr.map((value, index, arr) => {
  console.log(value, index, arr);
  return value * 2;
});

console.log(newArr);

/*
4 0 [ 4, 6, 7, 9, 2 ]
6 1 [ 4, 6, 7, 9, 2 ]
7 2 [ 4, 6, 7, 9, 2 ]
9 3 [ 4, 6, 7, 9, 2 ]
2 4 [ 4, 6, 7, 9, 2 ]
[ 8, 12, 14, 18, 4 ]
*/



let arr = [4, 6, 7, 9, 2];

arr.map(v => v*2).forEach(v => console.log(v));  //  8, 12, 14, 18, 4 

Filter

  • remove item that does not meet some conditions.
  • select all elements that meets the condition
  • returns a new array and this array consists elements that meets the filter condition.
  • Since this returns array, we can chain on this as well
let arr = [4, 6, 7, 9, 2];

const even = arr.filter(val => val % 2 === 0);
console.log(even); // [4,6,2]

Find

  • returns an item that meets some condition.
  • It return only the first element that meets condition.
  • returns single element and not an array.
let arr = [4, 6, 7, 9, 2];

const even = arr.find(val => val % 2 === 0);
console.log(even); // 4

Reduce

  • the parameters are accumulator, value, index, array
let arr = [4, 6, 7, 9, 2];

const sum = arr.reduce((acc, value) => {
  return acc = acc + value
}, 0);
console.log(sum);