Dormouse
Dormouse

Reputation: 5198

Weird Javascript For Loop Behaviour

I've got a for loop like this:

for (var i=first; i<=last; i++)
{
    $("#markers").append("<div class='marker'>"+i+"</div>");
}

first is set to 2001 and last is 2010. This works fine. The problem is when I change it to:

for (var i=first; i<=last; i+=1)
{
     $("#markers").append("<div class='marker'>"+i+"</div>");
}

(Notice the different final declaration is different). Any variation other than i++ results in an infinite loop. It's very strange as a jsFiddle with the same parameters works happily. Any suggestions?

Upvotes: 2

Views: 305

Answers (1)

drdwilcox
drdwilcox

Reputation: 3951

I would guess that first is set in a way that ambiguously could be interpreted as a string. So the first version can only be interpreted as increment, but the second is being interpreted by javascript as string concatenation.

Upvotes: 13

Related Questions