Lowering the condition for the loop

Can someone please help me understand why the following code works:

var someNumbers = [1,2,3,4,5];
var length = someNumbers.length;

for(var i=length; i--;) {
  console.log(i);
}

How does it know for a loop to finish once iequated to 0? What about negative numbers? Wouldn't that cause an endless loop?

+4
source share
3 answers

In Javascript, anything can be a condition! In this case, he i--. When it i--returns 0, the loop will stop because it 0is false.

- ( " ", . MDN for), /, "".

+7

for. MDN for , :


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

condition

, . true, . . , true. false, , for.

0 JavaScript - , false .

, for, , - , length, i, 1 , . i 0. for.

, length , , .

+2

 for(var i=length; i--;) {
    console.log(i);
     }

for (var i=length; i--;) &

 for (var i=length; i>0; i--)
    {
    console.log(i);
    }

It is not equivalent. The first cycle goes through length-1 to 0inclusively, and the second - length to 1. The first cycle easily rotates in an endless cycle. If the length is less than 0, the loop is infinite. It is definitely better to use the second form. Even longer, this is a safer and more readable version.

0
source

All Articles