Javascript higher order functions

What is higher order functions?

  • A function that takes or returns another function has become “higher-order”.
  • Higher-order functions let us abstract common actions like map, filter, and reduce.
  • Higher-order functions can be set as object properties.
  • They are useful if you are calling a list of functions in response to an event. The javascript Event loop works like this.
  • Referencing a function makes it easy to reuse, especially curried functions that take some params now and other later.

Examples:

Use filter() to check if a number is even of not

result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].filter(num => num % 2 === 0);
console.log(result); //[ 2, 4, 6, 8, 10 ]

Use map() to get names of all users in a array

users = [
  {
    name: 'John',
    age: 25
  },
  {
    name: 'Marry',
    age: 30
  },
  {
    name: 'Jack',
    age: 20
  }
];

userNames = users.map(user => user.name);
console.log(userNames); //[ 'John', 'Marry', 'Jack' ]

Check is name is starting with ‘M’ using filter

users = [
  {
    name: 'John',
    age: 25
  },
  {
    name: 'Marry',
    age: 30
  },
  {
    name: 'Jack',
    age: 20
  }
];
startsWithM = users.filter(user => user.name.toLowerCase().startsWith('m')); 
console.log(startsWithM); //[ { name: 'Marry', age: 30 } ]

Calculate the total age of all users using reduce()

users = [
  {
    name: 'John',
    age: 25
  },
  {
    name: 'Marry',
    age: 30
  },
  {
    name: 'Jack',
    age: 20
  }
];

totalAge = users.reduce((total, user) => user.age + total, 0 );
console.log(totalAge); // 75