Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
218,861 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.