Write Cleaner Code in JavaScript #3 Functions

The Atypical Developer
2 min readOct 9, 2022

--

This is the third part of the clean code series. If you wish to start from the beginning just click here!

Functions should do one thing

When functions do more than one thing, they are harder to compose. Additionally, testing becomes more difficult as each function must be tested for all of its different behaviours. Finally, reasoning about the code becomes more difficult as it is now harder to understand the effect of each function.

// Don't ❌function fixCars(cars) {
cars.forEach(car=> {
if (car.isBroken()) {
fix(car);
}
});
}
// Do ✅function fixBrokenCars(cars) {
cars.filter(isCarBroken).forEach(fix);
}

function isCarBroken(car) {
return car.isBroken();
}

Function names should say what they do

// Don't ❌function addToDate(date, month) {
// ...
}

const date = new Date();

// It's hard to tell from the function name what is added
addToDate(date, 1);
// Do ✅function addMonthToDate(month, date) {
// ...
}

const date = new Date();
addMonthToDate(1, date);

Don’t use flags as function parameters

As mentioned before, function should do one thing! If your functions are following different code paths based on a boolean, it is a good idea to split them out into separate functions. This will make your code more readable and easier to maintain.

// Don't ❌function updateProgress(score, progress) {
if (progress) {
navigate(`${progress}&${score}`);
} else {
navigate(score);
}
}
// Do ✅function updateLocalProgress(score) {
navigate(score);
}

function updateGlobalProgress(progress, score) {
navigate(`${progress}&${score}`);
}

Use max 2 function arguments

It is important to limit the number of function parameters because it makes testing the function easier. Having more than three parameters might lead to generating some issues, where you have to test many different combinations of arguments.

// Don't ❌function updateCarParams(engineSize, colour, parkingAssistance) {
// ...
}

updateCarParams(1.6, 'red', true);
// Do ✅function updateCarParams({ engineSize, colour, parkingAssistance }) {
// ...
}

updateCarParams({
engineSize: 1.6,
colour: 'red',
parkingAssistance: true,
});

Avoid negative conditionals

// Don't ❌function isCarDamaged(car) {
// ...
}

if (!isCarDamaged(car)) {
// ...
}
// Do ✅function isCarDamaged(car) {
// ...
}

if (isCarDamaged(car)) {
// ...
}

That’s it for functions. In the next part you’ll find clean code principles for comments in JavaScript.

--

--

No responses yet