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

whats the difference between inStock.indexOf(search) < -1 and inStock.indexOf(search) !== -1 ?

as the title says, I tried the program with if ( inStock.indexOf(search) !== -1 ) and if ( inStock.indexOf(search) < -1 ) and the reslt seems to be the same. my question is why to opt for one rather than the other.

thank you in advance ^^

2 Answers

Steven Parker
Steven Parker
218,694 Points

I'm surprised the difference wasn't noticeable. The value of "indexOf" should never be less than -1, so the test for "< -1" should never be true.

On the other hand, if an index is found, the method will return the index number of the match, which will be a non-negative integer. So testing for "!== -1" should be true anytime a match is found.

For future use, the "includes" method can do the same job as the latter but without the comparison. For example: "inStock.includes(search)". The result is true when a match is found.

what about the "find" method?

I tried "inStock.find(search)" but had no success...

Steven Parker
Steven Parker
218,694 Points

The "find" method syntax requires a callback function (instead of a string) as the argument.

I understand thank you very much ^^