jQuery.inArray() Fooled Me

·

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.

:facepalm:

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

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

I decided to use this:

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

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.

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Eric Binnion

Subscribe now to keep reading and get access to the full archive.

Continue reading