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

2 odd behaviours

I'm encountering 2 issues with this code, and I can't figure them out.

First, nothing is displaying in my browser window until after I type quit; then everything displays normally.

Second, if I search for apples, it says it is not in stock even though it is in the array.

My code is below--sorry, I couldn't get it to format correctly in the initial post.

3 Answers

I am not sure about the first problem you mentioned, but the reason why you are getting the message that says apples are out of stock is because the indexOf apples is 0. Since 0 is a falsy value your if statement does not pass. To get the desired behaviour try this:

if ( inStock.indexOf( search ) >  -1 ) {
  //...
}

Thanks--that solved the apples problem! Still no idea what is going on with the first issue, though. :(

It appears this might be a Safari thing. I tried it in Chrome and it worked as expected. Very odd.

var inStock = [ 'apples', 'eggs', 'milk', 'cookies', 'cheese', 'bread', 'lettuce', 'carrot', 'broccoli', 'pizza', 'potato', 'crackers', 'onion', 'tofu', 'frozen dinner', 'cucumber'];
var search;

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

while (true) {
  search = prompt("Search for a product in our store. Type 'list' to see all products or 'quit' to exit.");
  search = search.toLowerCase();
  if (search === "quit") {
    break;
  } else if (search === "list") {
    print( inStock.join(", "));
  } else {
    if ( inStock.indexOf( search ) ) {
      print( "Yes, we have " + search + " in stock.");
    } else {
      print( search + " is out of stock.");
    }
  }
}