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

Array shopping list

https://w.trhou.se/uqrhgxi3c8

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
11,817 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. :-)