Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,770 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