jQuery.inArray() Fooled Me

Put an Instagram filter on it

A couple of months ago, I found myself wanting to check if a value was in an array in JavaScript. Since I come from a PHP background, I was super excited to see that jQuery has an inArray() function.

So, I popped $.inArray() into the program, did a few tests to make sure it works, and then committed it. The next day I got a bug report…

Put an Instagram filter on it

Turns out that I forgot an edge case. What happens when the value I’m searching for is at the front of the array?

jQuery.inArray() Does Not Return a Boolean

Coming from a PHP background, I expected jQuery.inArray() to return a true if the value was found in the array and a false if the value wasn’t found in the array.

My mistake here is that I didn’t read the documentation well enough, or I would have seen that jQuery.inArray() is equivalent to using .indexOf().

So, instead of returning true when the value is found in the array, jQuery.inArray() was returning the index within the array where the value was found. If the value is not found, -1 is returned.


So, instead of having my conditional look something like this:

var numbers = [ 1, 2, 3, 4, 5 ];
if ( jQuery.inArray( 2, numbers) ) {
// do something

I decided to use this:

var numbers = [ 1, 2, 3, 4, 5 ];
if ( jQuery.inArray( 2, numbers ) >= 0 ) {
// do something

Lesson Learned

RTFM and Slow Down

We all require looking at the manual at some point when we program. Sure, there’s a few choice functions you use on a day-to-day basis for which you remember the parameters, order of the parameters, etc.

But, so much of a developer’s job is searching — Whether that’s on StackOverflow or Google. 30 more seconds would’ve been all it took for me to get it right.

Leave a Reply

Your email address will not be published. Required fields are marked *