Skip to content

About the author of Daydream Drift

Tomasz Niezgoda (LinkedIn/tomaszniezgoda & GitHub/tniezg) is the author of this blog. It contains original content written with care.

Please link back to this website when referencing any of the materials.

Author:

Suffering From ES6 Without Realizing It

Published

While writing syntax supported by ES6 I realized JavaScript is getting increasingly close to using up all possible and easy to use character combinations.

if (currentFileIndex => fileIds.length) {

Do you see what's wrong with the line of code above? At first glance it may seem that currentFileIndex must be greater or equal fileIds.length for the condition to pass. Instead, a condition like this one will always return true, because the => sign tells JavaScript to create an ES6 arrow function.

The correct one in this case would be >=. Unit tests may help spot this issue and JavaScript IDEs often color these two differently. Nonetheless, it's still very easy to overlook such a mistake while writing code. And it's not a syntax issue, so the compiler, whatever compiler it is, strict or not, won't warn of a possible misspelling. The best solution I came across is to use ESLint and its arrow-parens rule. It can warn about a possible misspelling of the comparison operator while the code is being written.

Most of the time arrow functions are written like this:

const add = (number1, number2) => {
	return number1 + number2
}

Or like this:

const add = (number1, number2) => number1 + number2

But there's another way. If only one parameter is provided to the function, the shortest solution is to write it like this:

const square = number1 => number1 ** 2

And this is the syntactic sugar that's the riskiest to use and the source of the problem discussed.

There are advantages to using arrow functions. However, ES6's added expressiveness also comes with a price.