Why is -1 false? - for (

The loop cycle works the way it was intended, but I just don't understand why.

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

: → 9.8,7,6,5,4,3,2,1,0

I searched google for false values : 0 and -0 .. (what does -0 mean?) But if 0 is considered false, why does the for loop get evaluated with it? Actually, the original code example looks like this:

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

It looks cool, but I just don't understand why it works.

+4
source share
2 answers

In the condition forin

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

iis evaluated to , decreasing (due to the operator after decrement). Therefore, it is 1 in the condition and 0 when you actually print it.

+7

, , , for:

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

9 0.

+1

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


All Articles