How to write readable functions

January 14, 2021
views 2 min read

I've been using this method for years now. Although I've come across this today and thought about sharing it.

As an example we'll take into account that we have a function that takes around 4 arguments, lets say to build a greeting sentence:

function buildGreeting(name, city, age, mood) {
  return `
    Hello ${name}. So you're ${age} years old
    and live in ${city}. Your current
    mood is ${mood}.

Alright, eventually we need to use this function right? Lets build a greeting then:

const greeting = buildGreeting('Telmo', 'Cartaxo', 34, 'happy')

greeting // Hello Telmo. So you're 34 years old and live in Cartaxo. Your current mood is happy.

This is fine. Although we can have some problems along the way.



One of the problem can be that we might want to send just 2 or 3 arguments, it would look something like:

buildGreeting('Telmo', null, 34, null)

It's getting messy already.

What is what?

I'm pretty sure eventually you'll forget the position of the arguments. Was name the first one or was age? Did this function had a mood argument?

buildGreeting(34, 'Telmo', null)

This will just return a messy sentence, not to mention we're missing an argument 😒


The way of fixing this is quite simple, we'll be sending an object into our function, not a bunch of arguments.

Our function would change to:

function buildGreeting({ name, city, age, mood }) {
  return `
    Hello ${name}. So you're ${age} years old
    and live in ${city}. Your current
    mood is ${mood}.

This way you know exactly what values belong to what arguments. You can even send the arguments in whatever order you want. While calling the function it can look a little longer, but trust me, your future self will thank you.

  age: 34,
  mood: 'happy',
  name: 'Telmo',
  city: 'Cartaxo',

That's it!

Read next
How to delete a git branch locally and remotely
February 10, 2021