Functional programming is a paradigm that results in cleaner and more concise code, that is easier to maintain, and reduces hard to find bugs. A central concept in functional programming is higher order functions. In JavaScript there a multiple of built in higher order functions.

According to Wikipedia a higher order function does one of the following:

  • takes one or more functions as arguments (i.e. procedural parameters),
  • returns a function as its result.

Filter

Lets get to it. In enterprise grade software, we sometimes want to filter on cute dogs.

const dogs = [

  { name: 'Cocker spaniel', cute: true },
  { name: 'Chihuahua', cute: false },
  { name: 'Malteser', cute: true },
  { name: 'Tax', cute: false }, 
]

We could use a for-loop for this. Where we would iterate over each dog and filter based on the cute boolean.

const cuteDogs = [];
for (let i = 0; i < dogs.length; i++) {
  if (dogs[i].cute)
    cuteDogs.push(dogs[i]);
}

However there is a much simpler solution, that is more elegant, that is using the filter function.

const cuteDogs = dogs.filter(dog => dog.cute);

#javascript #functional-programming #higher-order-function

Higher Order Functions in JavaScript
2.35 GEEK