tombraider
tombraider

Reputation: 1167

Why does this For loop crash the browser lab?

Probably a dumb question, but why is this simple loop crashing?

HTML:

<p></p>

JS:

var array = ["1", "2", "3", "4"];

for(var x = 0; x = array.length; x++) {
        $("p").html(array[x]);
}

Example Fiddle here.

Upvotes: 0

Views: 97

Answers (5)

RobertoB
RobertoB

Reputation: 72

Try x < array.length instead of x = array.length

Upvotes: -1

Nelson Teixeira
Nelson Teixeira

Reputation: 6562

You got 2 errors:

1st you don't test the condition. x = array.length; is an attribution not a comparison. You are atributting array.length to x instead of comparing them. The corret comparison statement would be:

x == array.length;

and 2nd, even if it were a comparasion it would exceed array length because array index it's zero-based.

so the correct would be:

var array = ["1", "2", "3", "4"];

for(var x = 0; x < array.length; x++) {
        $("p").html(array[x]);
}

Upvotes: 1

Mica&#235;l F&#233;lix
Mica&#235;l F&#233;lix

Reputation: 2775

Your loop is based on x, which is initialized with 0.

Your loop condition is evaluated by executing:

x = array.length 

That returns the value of x, not equal to 0, '', false, undefined or null so this condition will always be positive.

The loop continues to iterate, over and over again, always assigning x the same value, which does an infinite loop.

Upvotes: 0

Nils B.
Nils B.

Reputation: 26

As Long your array has keys your condition will be true, like a while loop.

var array = ["1", "2", "3", "4"];

for(var x = 0; x < array.length; x++) {
        $("p").html(array[x]);
}

This will stop on the last element.

Upvotes: 0

Amit
Amit

Reputation: 46323

Because x = array.length is not a "real" condition, and equality doesn't make sense in iteration anyway.

Try this:

for(var x = 0; x < array.length; x++) {
        $("p").html(array[x]);
}

Upvotes: 4

Related Questions