A Better Take on JavaScript’s Higher Order Functions.

Image for post

Functional Programming is awesome! It makes programming fun.

Learning to program “functionally” is going to make you a fantastic programmer and you will feel secure with the quality of your work.

Image for post

You will be able to write your programs with fewer bugs and in less time because you will be able to re-use your code.

Within this paradigm, we will focus on one of the most important concepts in functional programming, and that is Higher-Order Functions.


So let’s get started!

In JavaScript, and in many functional programming languages, functions are values.

Let’s take a simple function for example:

function double(x) {
  return x * 2
}

What is super cool about JavaScript is that we can take this function and make it into an anonymous function to pass it around and re-use it by declaring a variable.

let double = function(x) {
    return x * 2
 }

let pancake = double 
pancake(40) // 80

We declared a variable _double _and assigned it to the anonymous function. Then we declared another variable, pancake, and assign it to the same function. Just like strings and numbers, functions too can be assigned to variables.

So, in functional programming, functions are values and they can be assigned to variables and they can also be passed into other functions.

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. — see Eloquent JavaScript

In other words, as pertaining to our example, higher-order functions can be understood as functions being passed into other functions to do awesome things!!!

Sure, that makes sense, right? But what are these good for?

Composition.

The fact that we can take one function and put it into another function allows us to compose a lot of small functions into bigger functions.

Let’s look at how to use one of these higher-order functions. Probably the most basic and useful function is

Filter( )

Image for post

Image for post

Filter() is a function on the array that accepts another function as its argument, which it will use to return a new filtered version of the array.

Let’s make a fun array of something.

const pets = [

  { name: 'Flip flop', species: 'rabbit' },
  { name: 'Dino', species: 'dog' },
  { name: 'Ralph', species: 'fish' },
  { name: 'Chuchi', species: 'cat' },
  { name: 'Ari', species: 'dog' },
  { name: 'Spock', species: 'dog' },
  { name: 'ying yang', species: 'cat' },
]

What we want to do here is to just “filter” out all the dogs.

Our output must include Dino, Ari, and Spock. 😆

Question: How would I do this with a normal loop?

#higher-order-function #javascript #security #programming #code-review #function

Functional Programming: Higher Order Functions
2.10 GEEK