We need to talk about the one-liners.

For many years in my development career, it seemed everyone was pushing towards shorter code. If you could do the same thing in fewer lines it was better. But is it?

Rene Pot
JavaScript in Plain English
4 min readSep 25, 2021

--

Well… no. Often it is not better to write shorter code. End of the blogpost?

Well… again no. I think it requires a bit of clarification. Why the push for short code, and why is it bad? Or better yet, why can shorter code be bad. And I say can because longer code can make a mess. It’s all about code quality.

Let’s have a look at a simple if-else statement

if (numberOfThings > 5) {
proceed();
} else {
showError();
}

This is very clear, right? Easy to read, easy to follow, it flows well. Often this kind of code would be replaced with something like this

numberOfThings > 5 ? proceed() : showError();

Or maybe this

(numberOfThings > 5 ? proceed : showError)();

The functionality is identical, but it’s a one-liner. It’s shorter, but is it better? In simple situations, like the one illustrated above, it might be better but it’s already harder to read. Instead of 1 second, it might take 2 to read the code, more if you’re not very familiar with the short-hand if-else statement.

We’re still only dealing with 2 function calls, so this might actually not be too bad, but if it’s squeezed in between 100 other lines that make everything shorter too, will it be better?

But what if the functions it calls are short themselves, and you decide to omit the functions and just pull the logic into the if-else, then we’re getting something more horrible.

numberOfThings > 5 ? $.form.submit() : $.errormessage.text = “error message”; $.errormessage.show();

So now it already no longer fits on one line on Medium. It is still simple code, but do you prefer seeing this? Or do you prefer the function calls that have their own functionality?

Things get worse when a one-liner like this starts returning values, when there’s data transformation happening, or all of the above together. I’ve seen…

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Responses (1)

Write a response