I was reading jQuery’s documentation about the inArray method and I can’t really understand the meaning of one sentence. After saying that the method returns -1 if the element is not in the array, and 0 otherwise, it reads:
Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we’re checking for the presence of value within array, we need to check if it’s not equal to (or greater than) -1.
I can’t understand what the fact that JavaScript treats 0 as loosely equal to false has to do with the need to check the method’s return values. Would’t I need to do this even if JavaScript didn’t work this way?
It basically means that you need to write the test like this:
instead of:
The reason why you shouldn’t use the second construct is because if the value is the first element of the array the
inArrayfunction will return 0 (because that’s the index of the first element of an array) and as explained in the documentation0meansfalse: