hithere
hithere

Reputation: 520

Javascript for loops with negative numbers

Can anyone tell me why these javascript loops don't run?

for(var i = -5; i == 0; i++) {
    document.write(i);
}

https://jsfiddle.net/0h2p6uod/

for(var i = -5; i == -1; i++) {
    document.write(i);
}

https://jsfiddle.net/xb4k0sub/

for(var i = -5; i == 5; i++) {
    document.write(i);
}

https://jsfiddle.net/4bbatja9/

And yet, all of these loops run:

for(var i = -5; i < 0; i++) {
    document.write(i);
}

for(var i = -5; i < -1; i++) {
    document.write(i);
}

for(var i = -5; i < 5; i++) {
    document.write(i);
}

Upvotes: 1

Views: 531

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386540

The condition part is testing for true. If false, the loop stops.

for:

condition

An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.

for(var i = -5; i == 0; i++) {
//              ^^^^^^  false -> no loop

Upvotes: 4

afuous
afuous

Reputation: 1498

The for loop has 4 main parts:

for (initializer; condition; postoperation) {
    body;
}

It is equivalent to

initializer;
while (condition) {
    body;
    postoperation;
}

In your first example,

for(var i = -5; i == 0; i++) {
    document.write(i);
}

the condition is i == 0, so the loop will only continue when i is 0. But in the initializer, you set i to -5, so it stops immediately. If you change i == 0 to i != 0, it will continue as long as i is not 0, so it will stop when it reaches 0. You can do something similar for the other loops.

Upvotes: 3

Related Questions