Human-Readable JavaScript: A Tale of Two Experts

Everyone wants to be an expert. But what does that even mean? Over the years I’ve seen two types of people who are referred to as “experts.” Expert 1 is someone who knows every tool in the language and makes sure to use every bit of it, whether it helps or not. Expert 2 also knows every piece of syntax, but they’re pickier about what they employ to solve problems, considering a number of factors, both code-related and not. 

Can you take a guess at which expert we want working on our team? If you said Expert 2, you’d be right. They’re a developer focused on delivering readable code—lines of JavaScript others can understand and maintain. Someone who can make the complex simple. But “readable” is rarely definitive—in fact, it’s largely based on the eyes of the beholder. So where does that leave us? What should experts aim for when writing readable code? Are there clear right and wrong choices? The answer is, it depends.

The obvious choice

In order to improve developer experience, TC39 has been adding lots of new features to ECMAScript in recent years, including many proven patterns borrowed from other languages. One such addition, added in ES2019, is Array.prototype.flat() It takes an argument of depth or Infinity, and flattens an array. If no argument is given, the depth defaults to 1.

Prior to this addition, we needed the following syntax to flatten an array to a single level.

let arr = [1, 2, [3, 4]];

[].concat.apply([], arr);
// [1, 2, 3, 4]

When we added flat(), that same functionality could be expressed using a single, descriptive function.

arr.flat();
// [1, 2, 3, 4]

Is the second line of code more readable? The answer is emphatically yes. In fact, both experts would agree.

Not every developer is going to be aware that flat() exists. But they don’t need to because flat() is a descriptive verb that conveys the meaning of what is happening. It’s a lot more intuitive than concat.apply().

This is the rare case where there is a definitive answer to the question of whether new syntax is better than old. Both experts, each of whom is familiar with the two syntax options, will choose the second. They’ll choose the shorter, clearer, more easily maintained line of code.