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

Peter May
Peter May
16,376 Points

Why does the if statement "instock.indexOf(search) < -1" not work unless I change it to ">=0".

I couldn't get the search function to find stuff until I changed the if statement from ">-1" to ">=0". why doesn't it wrok with "-1"?

if(inStock.indexOf( search ) >=0 ){ print('yes we have '+ search+ ' in our stock.</p>'); } else{ print(search + ' is not in stock.');

Here is a link to my code.

https://w.trhou.se/dawof2rx73

2 Answers

Steven Parker
Steven Parker
229,644 Points

You've mentioned a few different comparison operations, only one would work.

  • if your test is " > -1", it should work
  • but " >= -1" would not work because it accepts the not-found condition (-1)
  • also " < -1" would not work because it is looking for other negative values

indexOf returns -1 if the element is not exists in the array. if the evultion of the expression returns a number above -1 it means that the element is inside the array- it give u back the index.