JS Tip of the Day: The Long Arrow Operator

The Long Arrow Operator
Level: Beginner

Over the recent years, a lot of attention has been given to arrow functions, a feature introduced in ES2015. And rightfully so; they provide some exciting, new functionality and a succinct format for writing functions. They’re sometimes called “fat arrow functions” because of the => used in their syntax. But these arrows aren’t the only arrows in town. Another arrow that you may not be hearing much about is the (unrelated) long arrow operator. This is written as -->.

The long arrow is an operator that counts a variable down to another number returning a boolean that determines whether or not the variable has not counted past its target value.

let counter = 3;
console.log(counter --> 0); // true
console.log(counter); // 2

console.log(counter --> 0); // true
console.log(counter); // 1

console.log(counter --> 0); // true
console.log(counter); // 0

console.log(counter --> 0); // false
console.log(counter); // -1

This works especially well in while loops letting you easily create loops counting down between two numbers.

let counter = 3;
while (counter --> 0) {
    console.log('count: ', counter);
}
/* logs:
count: 2
count: 1
count: 0
*/

Unfortunately, there is no count up variation of the long arrow operator. It only goes one way, and that way is down. The reason for this is that, in reality, the long arrow operator doesn’t actually exist. What you’re seeing is the behavior of two separate operators, the post decrement operator (--) and the greater than comparison operator (>).

Because whitespace is not important in the evaluation of these operators, by moving the decrement operator away from its variable and up against the greater than sign, it can look like an arrow. The end result is the same.

So:

let counter = 3;
while (counter --> 0) {
    console.log('count: ', counter);
}

Is actually the same as:

let counter = 3;
while (counter-- > 0) {
    console.log('count: ', counter);
}

When writing while loops that count down in this way, you may want to avoid this kind of spacing as it may confuse (…or maybe impress?) your colleagues. It can, however, be used as a reminder on how to write while loops that count down to a number. If you see the arrow in there, you’re doing it right.

More info:


More tips: JavaScript Tips of the Day

3 Likes

Did not know about this one at all! :stuck_out_tongue:

Clever stuff.
And you could be even more creative with this:

console.log(2 <++ counter)
console.log(counter ++> 2)