Welcome to the Treehouse Community
Looking to learn something new?
Justin Barreto4,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.
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!