JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

soufiane ez zine
soufiane ez zine
Full Stack JavaScript Techdegree Student 6,746 Points

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 ^^

3 Answers

Steven Parker
Steven Parker
182,603 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.

Christopher Evans
Christopher Evans
7,044 Points

what about the "find" method?

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

Steven Parker
Steven Parker
182,603 Points

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

Steven Parker
Steven Parker
182,603 Points

soufiane ez zine — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!