Adam Zerner

What are pure functions?

I've seen lots of people describe what pure function are. Most of them are ok, but there is one in particular that really clicked with me, and I'd like to share it with you. I got it from Eric Normand.

Consider the following function.

function sayHello(name) {
  return "Hello, " + name;
}

Here is how we can visualize it if it is called with an argument of "Alice".

But now imagine that we have some sort of global state representing the language.

const language = "spanish";

function sayHello(name) {
  if (language === "english") {
    return "Hello, " + name;
  } else if (language === "spanish") {
    return "Hola, " + name;
  }
}

Maybe we can visualize it like this?

I'd caution against that. There is something categorically different about the two inputs, and the visualization above implies otherwise.

Eric Normand says that name is an explicit input, whereas language is an implicit input. I really, really like that concept. name is explicitly being passed in to sayHello. You can see this clearly in the function's signature. But language is more implicit. Let's visualize it like this.

Let's take things even further. Imagine that we want to create a record in our database when they say hello. So in addition to returning the string, we hit our API as well.

const language = "spanish";

function sayHello(name) {
  let greeting;

  if (language === "english") {
    greeting = "Hello, " + name;
  } else if (language === "spanish") {
    greeting = "Hola, " + name;
  }

  axios.post("/greeting", greeting);

  return greeting;
}

Now our function is doing two different things. 1) It is returning a string. 2) It is hitting our API. Maybe we can represent that like this?

No. This has the same issue as before. There is something different about these two things: one is implicit, and the other is explicit. I'd visualize it like this instead.

Finally, with all of that out of the way, we are at the point where I can explain what a pure function is. A pure function is just a function with no implicit inputs or outputs. The only inputs are the arguments to the function. The only output is the return value. Pretty simple, right?

Now you might be having a lot of thoughts. Why would we want to avoid implicit inputs? Why would we want to avoid implicit outputs? Is doing so even possible? Practical?

Answering those questions is beyond the scope of this post. Sorry. It would be a pretty big rabbit hole to dive into, and I think it makes sense to separate the "what" from the "why". I can point you to some resources though. Check out this video on side effects and this book on functional thinking.


If you have any thoughts, I'd love to discuss them over email: adamzerner@protonmail.com.

If you'd like to subscribe, you can do so via email or RSS feed.

#code