The 'secret' goes to operator

The –> operator can be used in JavaScript, but what is it?

Run the following code:

let x = 3;
while ( x --> 0 ) {
    console.log(x);
}

and you will get the output:

2
1
0

But what is this mysterious --> ‘goes to’ operator? It doesn’t seem to exist in any documentation, yet clearly from the output above it must exist. Unfortunately, we haven’t discovered a secret operator, previously hidden from the JavaScript world. The --> operator is actually two operators: -- and >, the code is doing a greater than 0 comparison against x, and then decrementing the value of x after it has been evaluated (which is why when the first console.log(x) is evaluated it returns 2).

This is an example of how whitespace in your code can result in unexpected results, in this case, the code you are actually running is equivalent to:

let x = 3;
while ( (x--) > 0 ) {
    console.log(x);
}

Eslint

Using a linter such as eslint is a good way of avoiding problems such as this. Specifically, two rules are relevant in this case:

Require or disallow spaces before/after unary operators (space-unary-ops)

Some style guides require or disallow spaces before or after unary operators. This is mainly a stylistic issue, however, some JavaScript expressions can be written without spacing which makes it harder to read and maintain.

This rule can be used to enforce a space after any unary operators, so x --> y would always be written as x-- > y

disallow the unary operators ++ and – (no-plusplus)

Because the unary ++ and – operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code.

This is the more extreme version, banning ++ and – completely. The automatic semicolon insertion is for cases such as:

x
--
y

which evaluates as

x
--y

(but if you actually write code like that, I think you have more problems than a linter can fix…)

I don’t think this is necessary, but the rule does give you the option of banning it (or just issuing a warning when used).

Eslint and other tools such as Prettier can stop many similar problems, enforce good practices in your code and enforce your own team’s coding standards to ensure consistency across your code base. The rules can be set to automatically apply on save, so that you don’t have to think about the formatting more than necessary. I think automatic rule enforcement is a very useful tool, but can cause friction in a team environment as these rules can be very opinionated (Prettier, in fact, advertises itself as ‘An opinionated code formatter’, arguing that taking away all the choices reduces the burden on a team).

Written on May 3, 2018