Higher Order Functions

I’ve been reading “Eloquent JavaScript” by Marijn Haverbeke lately and today I rediscovered the idea of a higher-order function. I first encountered these in the freeCodeCamp curriculum, most likely, but I only glanced over them at the time.

Reading about it today though, everything clicked.

In JavaScript, you can declare a function in three ways.

let func1 = function(arg1){
  console.log("func1 called with", arg1);

function func2(arg1){
  console.log("func2 called with", arg1);

const func3 = arg1 => console.log("func3 called with", arg1);

The cool thing though is that through a mash up of these methods, you can define a function that creates other functions. An example makes this easier to understand:

function plusNum(num){
  return ans => ans + num;

let plusOne = plusNum(1);
let plusTwo = plusNum(2);

The Mashup

Using the func2 way of defining a function, we define a function plusNum. It’s super straight forward, it just returns a function definition in the func3 style, which you probably recogize as an arrow function.

Time for the crazy part: we want to define a new function, plusOne. The func1 style showed us we can let a variable take on a function definition as its value. Since plusNum() returns a function definition, after we give it a parameter of course, that means plusOne is a function in the func1 style of doing things!

A less wordy, more concrete explaination?

Looking at let plusTwo = plusNum(2). Let’s start with the right side. We call plusNum and give it a parameter 2. That returns a function, ans => ans + 2. We store this nameless little function in plusTwo, completely legally because function definitions are allowed to be the “value” for a variable. Done.

Too. Cool.

I don’t know what you would really do with this though. I’ve never had to customize functions like this before. At least I understand it now.

Thanks for reading this post! Comments, questions, and feedback are always welcome.

Thanks for reading this post! Comments, questions, and feedback are always welcome.