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.


Justin Barreto
Justin Barreto
4,267 Points

if ( inStock.indexOf( search ) > -1 ) Why do we need to include -1?

Can someone help explain why we need to include -1 in the if statement? I don't seem to get its impact in the code.

1 Answer

Nick Hericks
.a{fill-rule:evenodd;}techdegree seal-36
Nick Hericks
Full Stack JavaScript Techdegree Graduate 20,704 Points

Hey Justin, this is a really great question!

The first thing I notice in the code you have above is that the indexOf() method is being used within a conditional that is saying "call the indexOf method on this array named inStock, and if whatever is returned is greater than -1, evaluate the conditional as true and run the code below."

When looking at the documentation for indexOf() on MDN, we learn that...

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Ah-ha! So if the method finds the searched item within the inStock array, it returns the index of that item (Ex. 0, 1, 2, 3), however if the searched item is not found in the array, it will return -1. And in your conditional that would look like (-1 > -1) which is not true, so the conditional evaluates to false and the code below it does not run.

In short, the -1 is needed because indexOf() does not return a boolean (true or false) but instead returns a number. For that reason, when using it in a conditional, we need to evaluate that number against something.

Hope that helps! Keep on coding!