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

bobcat
bobcat
13,623 Points

I got uppers, downers....

Not sure why I cant get my indexOf( search ) method to run?

var inStock = ['ketamine','valium','uppers','downers','weed','hash','whiskey','meth'];

var search;

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

while ( true ){
search = prompt("Yo man, you need suttin\'? I got uppers, downers you name it. I can give you a full 'list' or you can just 'leave' "); 
    search = search.toLowerCase();
    if ( search === 'leave' ){
      break;
    } else if ( search === 'list' ){
      print( inStock.join(', ') );
    } else {
      if ( search === inStock.indexOf( search ) > -1 ){
        print('Yeah man, I got plenty of ' + search );
    } else {
        print('No man, I aint got no ' + search ); 
    }
  }
}

2 Answers

var inStock = ['ketamine','valium','uppers','downers','weed','hash','whiskey','meth'];

var search;

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

while ( true ) {
search = prompt("Yo man, you need suttin\'? I got uppers, downers you name it. I can give you a full 'list' or you can just 'leave' "); 
    search = search.toLowerCase();
    if ( search === 'leave' ){
      break;
    } else if ( search === 'list' ){
        print( inStock.join(', ') );
    } else {
        if (  inStock.indexOf( search ) >= 0 ){
          print('Yeah man, I got plenty of ' + search );
    } else {
        print('No man, I aint got no ' + search ); 
    }
  }
}

P.S You will see the "answers" just after you will type 'leave' because since this video recorded, Javascript updated and it can not print (document.write) through a loop.

bobcat
bobcat
13,623 Points

Hi Yuval, thanks for your quick response.

Your solution didn't help when I tried or answer why Dave's example in the video worked and mine didn't. I went back and started from scratch and now it works the same as the example in the video, so I assume I was missing a curly brace or it was a typo.

I was using Firefox so the list and responses appeared as soon as I asked in the prompt unlike chrome which waits until you break from the loop to print the answer.

Thanks anyway.