TwoFiveOne
TwoFiveOne

Reputation: 45

why -1 is falsy ? - for (

The for loop bellow works as it was intended, but I just do not understand why.

for (var i = 10;i--;) { 
    console.log("i: " + i); 
}

console: >> 9,8,7,6,5,4,3,2,1,0

I googled for the falsy values: 0 and -0 .. (what does -0 mean ?) But if 0 is considered to be falsy, why the for loop gets evaluated with it ? Actually the original code sample actually look like this:

for (var i = e.length; i--; )
    e[i].apply(this, [args || {}]);

It looks cool, but I just do not get why it works.

Upvotes: 4

Views: 88

Answers (2)

A.L
A.L

Reputation: 10483

Roberto Reale explained the reason, but I think this problem can also be solved by using the 3 statements in the for loop:

for (var i = 9; i >= 0; i--) { 
    console.log("i: " + i); 
}

It will display integers from 9 to 0.

Upvotes: 1

Roberto Reale
Roberto Reale

Reputation: 4317

In the for condition in

for (var i = 10;i--;) { 
    console.log("i: " + i); 
}

the i is evaluated before being decreased (due to the post-decrement operator). Hence it is 1 in the condition and 0 when you actually print it out.

Upvotes: 7

Related Questions