hithere hithere - 8 days ago 7
Javascript Question

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);
}

Answer

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.

Comments