JavaScript Refactoring Tips — Making Functions Clearer and Cleaner

John Au-Yeung
Level Up Coding
Published in
4 min readApr 27, 2020

--

Photo by Roxana Baciu on Unsplash

JavaScript is an easy to learn programming language. It’s easy to write programs that run and does something. However, it’s hard to write a piece of clean JavaScript code.

In this article, we’ll look at how to make our functions clearer.

Using Destructuring for Object Parameters

If we want our function to take lots of arguments, then we should take one big object argument.

To do that, we should use the destructuring syntax to destructure the properties of the object we pass in as the argument as variables.

For instance, instead of writing:

const greet = (obj) => {
return `${obj.greeting}, ${obj.firstName}${obj.lastName}`;
}

We should write:

const greet = ({
greeting,
firstName,
lastName
}) => {
return `${greeting}, ${firstName}${lastName}`;
}

This way, we have a lot less repetition, and it makes everyone clear what properties the object has in the arguments.

It’s like having multiple arguments without actually having to pass in multiple arguments.

It’s a lot more flexible as the order of properties in an object doesn’t matter as with multiple parameters, but we still can access each property individually as variables.

Naming Our Callback Functions

Naming things makes reading code easier. This is the same with callback functions. For instance, instead of writing:

const arr = [1, 2, 3].map(a => a * 2);

We should instead write:

const double = a => a * 2;
const arr = [1, 2, 3].map(double);

Now we know that our callback function actually is used for doubling each entry of the original array.

Make Our Conditionals Descriptive

Conditionals can be made more descriptive by writing the conditional expressions in a conditional statement in their own function.

For instance, instead of writing:

if (score === 100 ||
remainingPlayers === 1 ||…

--

--