DEV Community

Cover image for Demystifying the Long Arrow "Operator"
Basti Ortiz
Basti Ortiz

Posted on • Updated on

Demystifying the Long Arrow "Operator"

I recently stumbled upon some code that I found to be really interesting. It essentially iterates over a loop but with a twist. It uses the mysterious long arrow "operator".

const pets = ['Lucky', 'Sparkles', 'Presto', 'Fluffykins'];
let i = pets.length;

// A wild LONG ARROW OPERATOR appeared!
while (i --> 0) {
  console.log(pets[i]);
}

// 'Fluffykins'
// 'Presto'
// 'Sparkles'
// 'Lucky'
Enter fullscreen mode Exit fullscreen mode

What's interesting and unusual about this "operator" is the fact that it iterates over the pets array in reverse, as seen in the console output. It seems that writing i --> 0 is like counting down to 0. Lo and behold, it actually is counting down under the hood.

The Magic Behind the "Operator"

In this article so far, the use of quotation marks around the word "operator" has been no coincidence. The long arrow "operator" is not really an operator, so to speak. It's more accurately a combination of two operators.

The long arrow "operator" (-->) is just a combination of the postfix decrement operator (--) and the greater than operator (>).

Since JavaScript ignores whitespace most of the time, we can cleverly format our code in such a way that glues -- and > together into -->. Instead of saying x-- > 0, we can write x --> 0. Regardless of format, JavaScript will interpret the long arrow "operator" as two separate operators.

NOTE: If it seems strange that x-- can be used for numerical comparisons, I wrote an article recently about the nuances of the increment and decrement operators. You can read about it here.

// All of these _output_ the same thing to the console.
// EXAMPLE 1: Good ol' `while` loops
let a = 5;
while (a > 0) {
  a--;
  console.log(a);
}

// EXAMPLE 2: Good ol' `for` loops
for (let b = 4; b >= 0; b--) {
  console.log(b);
}

// EXAMPLE 3: Combination of two operators
let c = 5;
while (c-- > 0) {
  console.log(c);
}

// EXAMPLE 4: Long arrow "operator"
let d = 5;
while (d --> 0) {
  console.log(d);
}
Enter fullscreen mode Exit fullscreen mode

Don't ditch the loops

So there you have it. The mysterious long arrow "operator" is just a combination of two operators. I think it's a pretty nice way of reading code because of how analogous it is to the notation of limits in calculus.

With that said, here is a list of the many ways I would read x --> 0.

  • "as x approaches 0"
  • "x goes to 0"
  • "count down x to 0"
  • "decrement x until it reaches 0"
  • "subtract 1 from x until it reaches 0"

Although the long arrow "operator" looks nice to read, I wouldn't write my code with it. The code formatting is just too clever. At first glance, especially for someone new to the language, it does not seem intuitive at all. One can quickly search Google about some long arrow "operator" in JavaScript, Java, or C++ just to find out that there aren't many resources about it.

It's just not "beginner-friendly" enough, which is why I don't like it. One has to be aware of the return value of the postfix decrement operator to fully grasp why such code is even syntactically correct. Beginners should never bother with the intricacies of a programming language to learn it. Explicit is better than implicit, as they say.

Besides that, the long arrow "operator" acts like a countdown. As a consequence of this, it iterates on arrays in reverse, which may not exactly be a desired behavior in some cases.

To summarize, the long arrow "operator" is a clever way of formatting two different operators. Unless you (and your peers) are fully comfortable with reading long arrow notation or you just want to impress your friends with some strange syntax they have never seen before, it is better to stick with for loops for general-purpose iteration.

Oldest comments (63)

Collapse
 
worc profile image
worc

seems like an excellent way to frustrate the hell out of future maintainers. the formatting is weird and the value you declared for your index is never used. that's subtle and unexpected (two things you should never be striving for in code meant to be read by humans).

Collapse
 
beernutz profile image
beernutz

The value for the index is used, it is just used in a confusing way.
This whole article is just an example of what NOT to do.

Also, realize that the post decrement actually happens AFTER the comparison to zero, which might not be obvious to someone as well. As you say, don't do this with code that someone else might have to maintain.

Collapse
 
worc profile image
worc

i should clarify, the problem that stood out to me is the initial value of the index is never used in the body of the loop. that's what makes this thing so awful. the loop "works", but then you're left chasing an off-by-one error.

Collapse
 
somedood profile image
Basti Ortiz

Well, the point of this article isn't really to encourage you to use it, thus my recommendation against it towards the end of the article. It's just a fun way of reading code.

In the bright side, at least you now know what that weird long arrow means in some code bases if ever you encounter them.

Collapse
 
differentsmoke profile image
Pablo Barría Urenda

Come on, you don't discourage it nearly enough as you should if that was indeed your intention. This isn't something that "beginners shouldn't be doing", this is something that no one should be doing. Saying something isn't "for beginners" isn't condemnation, it's just motivation for aspiring ninjas. There's no upside to using this "operator": Long Arrow "operator" considered harmful.

Thread Thread
 
somedood profile image
Basti Ortiz

Don't worry. I'm pretty sure the comments section has discouraged its usage strongly enough. It's fascinating how passionate everyone is against the way of formatting such code.

Collapse
 
beernutz profile image
beernutz • Edited

That is just a bad idea.

There really is no such thing as a "Long arrow" operator.

The example of:

while (i --> 0) {
  console.log(pets[i]);
}

Is really just:

while (i-- > 0) {
  console.log(pets[i]);
}

The post decrement does not belong to the greater than sign, and implies entirely different things.

Collapse
 
somedood profile image
Basti Ortiz

Exactly the point I tried to hit on. I purposefully added quotation marks around the word "operator" every time I used it in the context of the "long arrow operator" because of that.

Collapse
 
beernutz profile image
beernutz

But that is the problem. There is no such thing as a "long arrow operator", and you are just sowing confusion.

Thread Thread
 
somedood profile image
Basti Ortiz

I see. I get your point. I wrote this article so that people would be aware of an unorthodox way of formatting their code, so that when they encounter them in the wild, they'd be prepared to tackle them.

Indeed, the entire point of this article is to demystify something that doesn't exist. It's great that you pointed this out, though.

Collapse
 
worc profile image
worc • Edited

but you also called it analogous to a limit function. which is confusing and it's just not. limits in my mind are inclusive, infinite sequences, not integer-based, step-wise functions that forget their initial value.

Thread Thread
 
somedood profile image
Basti Ortiz

That's true. I do catch your drift. I see where I might have caused some confusion there.

It isn't meant to equate the two ideas, though. One shouldn't get too worked up in it. It is just an analogy after all.

Thread Thread
 
worc profile image
worc

i think the issue is that it's a bad analogy. it draws parallels where there are none, and it creates a mind map that just doesn't match the terrain.

Thread Thread
 
somedood profile image
Basti Ortiz

That's true. This isn't the first time I've made bad analogies. Guess I'm still learning how to play with my words in an interesting manner. I'll keep working on it.

Admittedly, though, I don't see the analogy I made as entirely wrong. There is still some truth to it. The notation does imply some sort of "approaching by decrementing" to an extent. Regardless of that, it's still a bad analogy, as you said, and I agree.

However, I won't edit the article because that's really how I thought about the notation at first. It would really be dishonest of me and to myself if I changed the analogy now. So for now, it shall serve as a reminder to me to be better with my analogies.

Thread Thread
 
worc profile image
worc

The notation does imply some sort of "approaching by decrementing"

i think the issue is that "approaching by decrementing" just isn't a limit. if you'd stumbled across a "approach through an infinite sequence" operation (maybe something that recursively takes smaller steps as it approaches a correct answer?), then i think you'd be on to something.

Thread Thread
 
somedood profile image
Basti Ortiz

I see. I get your point.

Collapse
 
caseycole589 profile image
Casey Cole

while(i--) is better

Collapse
 
ourmikegeorge profile image
Mike George

Did you mean nuisances or nuances? Maybe both?

Collapse
 
somedood profile image
Basti Ortiz

Definitely both. 😂

 
somedood profile image
Basti Ortiz

Oh. Thanks, man. Appreciate it! 👍

Collapse
 
joelnet profile image
JavaScript Joel

Creative! I love weirdness like this.

The only problem with it is that it requires reeducation. And people really resist being educated.

Perfect for a pet project. Not so much for your employer's source.

You'd just have to add some docs to explain what this funky thing does.

Cheers!

Collapse
 
somedood profile image
Basti Ortiz

Thanks! I'm glad you share my fascination with weird things. *high five*

Collapse
 
joelnet profile image
JavaScript Joel

Keep em coming!

Collapse
 
worc profile image
worc

it's not really a "reeducation" problem so much a bad code problem. it might be useful for code golf, but it's just a confusing way to decrement an index.

Collapse
 
puritanic profile image
Darkø Tasevski

But why? I don't see how this can be useful at all O.o So please don't make this as an actual thing.

Collapse
 
somedood profile image
Basti Ortiz

Oh, for sure! You share the same sentiment as everyone who read this article (including me). 😂

I just wanted to show that there is an unorthodox way of writing two separate operators. That way, when one encounters such code in the future, they'd be ready to tackle it.

Collapse
 
andrerpena profile image
André Pena

This is a total click bait title. Dismistifying something that doesn't exist. 🤔

Collapse
 
somedood profile image
Basti Ortiz

Aren't all "mysteries"? 😉

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
somedood profile image
Basti Ortiz • Edited

I believe I hit on that point pretty explicitly in the article. Somewhere around here, I think?

Collapse
 
mogery profile image
Gergő Móricz

TL;DR: x --> 0 = x-- > 0

Collapse
 
somedood profile image
Basti Ortiz

YUP. Can never agree more. 😂

Collapse
 
gsmoffln profile image
gsmoffln

You probably meant,
x --> 0 == x-- > 0?

No, no, and no.

--> is a recognized ES token in every popular browser. If it occurs at the start of a line, it is considered a single-line comment.

Collapse
 
dimpiax profile image
Dmytro Pylypenko • Edited

In 12 years of the programming, I first hear about "long arrow" operator. It confuses beginners.
But you can do the same, in easy way:

let x = 2
while (x--) { 
  console.log(x)
} 
// 1
// 0
Collapse
 
somedood profile image
Basti Ortiz

Yup, that's definitely true. In cases when one has to decrement until any number other than 0, I think the long arrow "operator" has its... "uses".

let i = 10;
while (i --> 5) {
  console.log(i);
}
Collapse
 
dimpiax profile image
Dmytro Pylypenko

Nowadays decrement and increment are bad practice. Consequently operator "long arrow" will be disappeared, and it's good.

Thread Thread
 
cecilelebleu profile image
Cécile Lebleu

If you don’t mind me asking, why are decrement and increment considered bad practice? They seem relatively simple and straightforward.

Thread Thread
 
somedood profile image
Basti Ortiz

Honestly, I don't consider it bad practice myself. I agree with your sentiment. It's just that it's only bad practice in the context of the "long arrow operator".

I'll let others answer your original question for you. I'm sure it has turned up in one of the discussions at some point.

Thread Thread
 
dimpiax profile image
Dmytro Pylypenko

In whole context,

  1. It has some bad relation with compiler optimizations. Don’t know what we have nowadays.
  2. It’s not good for abstraction. I.e.: ‘value += iterateAmount’.
Collapse
 
okdewit profile image
Orian de Wit

Watch out with that notation though, it's best to only use it on integers declared as a constant.

let x = 2

// Wait, you have to pay taxes over your loops!
x *= 1.1

while (x--) { 
  console.log("Nothing can be said to be certain, except death and taxes")
} 
Collapse
 
dimpiax profile image
Dmytro Pylypenko

You need to know what you are doing with your code.

Thread Thread
 
okdewit profile image
Orian de Wit

Certainly! But with Javascript not having an int type, it can lead to unexpected bugs.

Sometimes the space between the declared variable and the loop fills up with other code, especially in a project that's not squeaky clean to begin with.
Or the variable was passed in as an argument to a function, and eventually someone calls the function with unexpected input.

Maybe a coworker wants to loop over something in batched chunks, and naively divides x by a chunkSize.

Assuming that x in while(x--) is an integer which will hit zero isn't necessarily bad, just something to be careful with.

Thread Thread
 
dimpiax profile image
Dmytro Pylypenko • Edited

It's true that it is dangerous.
I see a reason to use tools (approaches) in related situations.
Construction without zero only in the case, when you know what you do. For example, iterate through array elements from the end:

const arr = ["this", "is", "c", "h", "a", "r"]
let n = arr.length
while(n--) {
  const el = arr[n]
  ...
}

or count input value as a number. In this case, input can be any, the function must know the type and cast to it. If float – make it as int by parseInt or Math functions.

Collapse
 
theodesp profile image
Theofanis Despoudis

Tha'ts why everyone should avoid increment (++) and decrement (--) operators:

Collapse
 
theodesp profile image
Theofanis Despoudis

That's why everyone should avoid increment (++) and decrement (--) operators

As in the Douglas Crockford's Javascript: The Good Parts, he writes:

++ and --
The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by
encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option [in JSLint] that prohibits the use of these operators.

Collapse
 
somedood profile image
Basti Ortiz

Definitely can't disagree with the Great Crockford.

Collapse
 
akashdeepsingh profile image
Akashdeep Singh • Edited

This article is a much needed resource for someone who might come across such usage and google it. I agree that it shouldn't be used because it relies on whitespace formatting and in fact, deceives the reader into thinking it's a single legitimate operator.

I suggest adding names of languages that accept this usage in the title? And perhaps a clarification in the beginning that the "long arrow operator" doesn't actually exist.

Collapse
 
somedood profile image
Basti Ortiz

I'm sure the comments section have clarified those facts strongly enough. 😂

Collapse
 
tehpsalmist profile image
Ben Steward

Looks beautiful with my font ligatures!

Kewl Kode

Oh, what's that? A reverse long-arrow operator? Read about it here!

Collapse
 
cecilelebleu profile image
Cécile Lebleu

You are evil.