JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

Colin Sygiel
Colin Sygiel
5,249 Points

I think my code is causing a crash due to infinite loop - Any help?

var inStock = [ 'apples', 'eggs', 'milk', 'cookies', 'cheese', 'bread', 'lettuce', 'carrot', 'broccoli', 'pizza', 'potato', 'crackers', 'onion', 'tofu', 'frozen dinner', 'cucumber'];
var search;
var message = "There is " + search + " in stock.";

function print() {
document.write( '<p>' + message + '</p>');
}

while (true) {

if (inStock.indexOf( search ) > -1) {
print(message);
}
else {
search = prompt("What are you searching for?");
}

}
Franklyn Roth
Franklyn Roth
16,769 Points

It is indeed an infinite loop. I think what is going on is that you set the conditional to true in the while loop.

while(true). It starts out as true, and it always true..so it keeps on running. I think what you want is

while(what you've search is in stock) or something along those lines? I'm not up to this point yet.

Colin Sygiel
Colin Sygiel
5,249 Points

Thanks Frank, the instructor sets it to true, but something else must be going on.

1 Answer

You created an infinite loop like what the instructor did. However, you did miss one very important thing that the instructor did do. You forgot to break the loop under some condition :)

Since you didn't break out of the loop, the loop will just run forever. :smile:

Try reviewing this video to learn more about breaking out of loops.

Good luck! ~Alex