Week 3: Higher Order Functions

In a week full of client work, Saturday morning will have to be JavaScript time this week.

Posted 29th June 2019 • JavaScript • #javascript #learning

I've gone back and forth on including cover images on blog articles. Do you know how difficult it is to find a different JavaScript stock photo to use every week? In general I'm a fan of only including imagery on a site when it serves a purpose or is useful, so I tried taking the images off the blog as I thought they were there purely for decoration. Turns out that without the cover images, it just looks like a long list of text and not only is it more boring to look at, it's also a more confusing layout for finding articles. So that's it, you get an unrelated picture of books about coffee today.

When I started looking for something new to learn, it was because I'd had a lull in client work and wanted to make use of the time to increase my skills. That lasted all of two weeks, and having had a few days off, I had emails about 6 new projects all on the same day this week, so things have started ramping up again and JavaScript went out the window. As I've said before, practising every day even for only 5 minutes helps keep the brain engaged with the subject, and that went out the window this week (11 hour days will do that). I needed to do -something- this week to have something to write about though, so I ran through the next module on Codecademy this morning; Higher Order Functions.

Higher Order Functions is a concept whereby you can use functions as arguments in other functions, or return a function as a result. It sounds complicated, but with a practical example it's pretty easy to see why it's useful (at least in theory). First though, a minor useful thing:

// This really long function name checks that 2 + 2 is 4, a million times
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong');

// You can re-assign the long function name to another name, like an alias
const is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;

// Run the new function name

// Outputs checkThatTwoPlusTwoEqualsFourAMillionTimes

You can also use functions as parameters for other functions:

const timeFuncRuntime = funcParameter => {
   let t1 = Date.now();
   let t2 = Date.now();
   return t2 - t1;

const addOneToOne = () => 1 + 1;


The code above would run timeFuncRuntime, which takes a function as an argument, saves the start time, invokes the callback function, records the time after the function was called, and returns the time it took to run by subtracting the starting time from the ending time.

Finding this interesting?

Get in touch