Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 241
TwoFiveOne Avatar asked Feb 13 '23 20:02

TwoFiveOne


1 Answers

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.

like image 74
Roberto Reale Avatar answered Feb 15 '23 10:02

Roberto Reale