Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good reason to avoid FOR loops without a final-expression in JS?

Is it a bad habit to write reverse loops as:

for (i = N; i--;)

in order to access (N-1) to 0

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

like image 319
Sinetheta Avatar asked Dec 02 '22 23:12

Sinetheta


2 Answers

There's no technical reason that this won't work. However, it clearly has readability issues since someone had an immediate "well that won't work!" reaction.

This is the kind of issue that the jQuery team struggles with – whether to use novel constructs that save bytes at the expense of clarity and maintainability. It really comes down to whether it's worth 1 or 3 bytes of savings:

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

In this case, probably not.

like image 156
josh3736 Avatar answered Dec 22 '22 09:12

josh3736


It is less readable, without your explanation it would take me few seconds to understand what the loop does. Why not simply:

while(i-- > 0)

?

like image 40
Tomasz Nurkiewicz Avatar answered Dec 22 '22 10:12

Tomasz Nurkiewicz