Is there any good reason to avoid FOR loops without the final expression in JS?

Is it a bad habit to write back loops like:

for (i = N; i--;) 

to access (N-1) to 0

If so, why? jsLint certainly doesn't like it.

+4
source share
6 answers

There is no technical reason that this will not work. However, it clearly has problems with readability, as someone had an immediate β€œwell, that won’t work!” reaction.

This is the problem that the jQuery team is struggling with - should we use new designs that save bytes due to clarity and maintainability. It really boils down to whether 1 or 3 bytes of savings are worth it:

 for(var i=9;i--;) var i=9;while(i--) for(var i=9;i>0;i--) 

In this case, probably not.

+6
source

This is less readable, without your explanation it would take me a few seconds to figure out what the loop is doing. Why not just:

 while(i-- > 0) 

?

+4
source

Did you consider readability? You can understand this very well, but other developers can get confused, as the for "idiom" parts are usually called :

 for ([initialization]; [condition]; [final-expression]) 

While a condition can be technically any expression, your version does not match this idiom, since the part of the β€œcondition” that you use does more than just define the condition - it also shortens i .

+4
source

"Bad habit of writing reverse loops:"

 for (i = N; i--;) 

This is a matter of opinion, but it is actually the opposite of while initializing, so in my opinion this is not a "bad habit". This is just a coding style.

The specification makes for parts optional to give the developer flexibility.

"jsLint certainly don't like it."

Who cares. You are not required to follow the opinions of jsLint.

+2
source

The answers would be very subjective, I think. I don't think this is a bad habit, but I find it aesthetically uncomfortable. This can be expressed more elegantly, for example:

 for (i = N - 1; i >= 0; i--) { // do something here. } // And if it is really important that i should be 0 here // as it is in your original code. i = 0 

This code is easier in our brains when viewing a large amount of code that contains this.

+1
source

Yes. There is a good reason. Readability.

+1
source

Source: https://habr.com/ru/post/1394690/


All Articles