user3398326
user3398326

Reputation: 544

loop statement in javascript not behaving as expected

The below code will only execute the alert statement statement once then break. For example i = 2000 i was expecting it to be printed 4 times will it reaches the condition.

var i = str.value;

for (i; i <= 2400; i += 100) {
    alert(i);
}

Upvotes: 1

Views: 35

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

If the type of str.value is a string, then it execute for the first time, the next time it will fail, because

i += 100

will concatenate 100 as a string to 2000, instead of adding. You can check that like this

console.log('2000' + 100);
# 2000100

which will be greater than 2400

console.log('2000100' > 2400);
# true

So, you should be converting i to an integer, like this

var i = parseInt(str.value, 10);

with that change, the output becomes

2000
2100
2200
2300
2400

Upvotes: 5

Related Questions