Array shopping list

Hello, I have the below result after running and selecting bread from the array list. Bread is the very first item which i thought may produce 0 instead of -1 however in either case would anyone know how to return:- Yes we have bread, its number 1 on the list!

Sorry i have just answered my own question by adding + 2
my code is now updated to:- message = Yes we have ${search}, its number ${inStock.indexOf() + 2} on the list!; could someone tell me why this happens, thanks.

What my code currently returns:- Yes we have bread, its number -1 on the list!

1 Answer

Cameron Childres
Cameron Childres
Treehouse Moderator 10,935 Points

Hi jasonj7,

The indexOf() method will always return -1 if it does not find the value in the array. Right now you will receive -1 for every value given to the prompt. This is because you have not passed any value to indexOf().

You can fix this by passing the "search" variable to indexOf():

if ( inStock.includes(search) ) {
    message = `Yes we have ${search}, its number ${inStock.indexOf(search) +1} on the list!`;
} else {
    message = `Sorry we dont have ${search} in store.`;

Since the index starts at 0, adding 1 will display its proper position in the list.

One other note -- the message in your else statement currently uses quotes. Change this to backticks so that the string interpolation for ${search} functions correctly.

I hope this helps! Let me know if you have any questions.

Hi Cameron Childres, yes I did notice my error not using backticks for ${search}, I just remembered a similar situation of +1 when its comes to random numbers and we don't want a random number of 0 so we add +1.
Thanks very much for your response you have helped greatly. :-)