30 Days Of JavaScript

Day 6: Functions Part 2

Lesson 3: Functions as inputs

So, why does it matter that this syntax makes it obvious that functions are just objects that we can pass around?

Well, it means we can pass them in to other functions 🤯

Let that sink in for a second. In 24 hours we've gone from learning about these things called functions, that can take inputs, to now being told that functions can be passed into other functions as other inputs!

This is a big idea, a core part of how JavaScript works, allowing a huge amount of power and flexibility to developers. I'm going to introduce you to this slowly with some slightly silly examples.

Let's say we have out unit conversion function:

1const convertMeasurement = (measurement, unit) => {
2  if (unit === "cm") {
3    return measurement / 2.54;
4  } else {
5    return measurement * 2.54;
6  }

It takes a measurement and it's unit then gives you converted unit of cm or inches.

What if in some cases we want to log inputs and outputs?

Well we could add the logging around the main code, like this:

4const result = convertMeasurement(length, unit);

But this is getting a bit messy. We can create a new function called logInOut() that will bundle this up for us.

In this playground you can see we create the conversion function like always, then we create a new function called logConversionInOut that takes the same inputs AND an input called func (we can't call it function as that is a reserved word in JavaScript).

When we call logConversionInOut we pass it the measurements, the units and then the the convertMeasurement function.

Notice we don't add the () at the end of convertMeasurement. We want to pass a reference to the function, we don't want to execute it ... yet.

Inside logConversionInOut we log the inputs and then we call func and pass in the arguments it needs (measurement and unit). We then get the result, log it and then return it.

You might already recognise that we could make this quite generic and have it log the inputs and outputs of any function that has two inputs and returns value.

Here's another example:


In the playground below take the more generic logInOut from the playground above and pass in the convertMeasurement function from the playground above that.


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co