Search the blog

I recently used jQuery’s $.inArray and found it wasn’t working. Intutively, I thought this would be the right code:

if ($.inArray(value, array) === false) { //...

This doesn’t work. jQuery tell us why this is (from api.jquery.com/jQuery.inArray/):

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), to check for the presence of value within array, you need to check if it's not equal to (or greater than) -1.

Therefore, this is the correct way to do it:

if ($.inArray(value, array) !== -1) { //...
Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.