jQuery.inArray(), how to use it right?

inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.

So, to check if an item is in the array, use:

if(jQuery.inArray("test", myarray) !== -1)

The right way of using inArray(x, arr) is not using it at all, and using instead arr.indexOf(x).

The official standard name is also more clear on the fact that the returned value is an index thus if the element passed is the first one you will get back a 0 (that is falsy in Javascript).

(Note that arr.indexOf(x) is not supported in Internet Explorer until IE9, so if you need to support IE8 and earlier, this will not work, and the jQuery function is a better alternative.)


$.inArray returns the index of the element if found or -1 if it isn't -- not a boolean value. So the correct is

if(jQuery.inArray("test", myarray) != -1) {
    console.log("is in array");
} else {
    console.log("is NOT in array");
}