# The stones of my mind

In the post about Google Maps using the scroll wheel for zooming instead of scrolling, I mentioned that although I knew perfectly well that Google was doing this, I just couldn’t stop myself 1 from trying to scroll that way. Last night, as I was adding a spam detection function to Dr. Twoot, I ran into a similar mental block that I just can’t get around.

This block involves the inArray utility function provided by the jQuery JavaScript library. It’s a really handy function: you pass it an item and an array, and it searches the array to see if that item in it. Sort of like the x in s operator in Python.

It’s the “sort of” part that always gets me. While x in s returns True if item x is in list s and False if it doesn’t, inArray(x, s) does something a little different. It returns the index of x if x is in s and returns -1 if x isn’t in s.

You can probably see where my problem is. JavaScript allows numbers to act as Boolean values, but the numbers inArray returns aren’t in the right form to be used that way. Like many C-derived languages, JavaScript takes 0 to be false and any other number to be true. Unfortunately, 0 is a perfectly valid array index, so if you do something like

javascript:
if ($.inArray(x, s)) { alert("It's in there"); } else { alert("It's not in there"); }  it won’t do the right thing if x is the first item of s. Just as bad, it’ll also do the wrong thing if x isn’t in s because -1 is considered true. There are now three places in the Dr. Twoot code where I use inArray to test an item’s membership in an array. In every case I have initially used it incorrectly, like the snippet of code above, instead of correctly, like this: javascript: if ($.inArray(x, s) > -1) {

}
else {

As with my Google Maps scroll wheel confusion, part of the problem certainly lies with jQuery. The name inArray makes it sound like a function that returns a Boolean. But all languages have their quirks, and I can usually keep them straight. This one, though gets me every time.
Real JavaScript programmers are probably shaking their heads sadly and wondering why I don’t just use the native indexOf method. Its name is much more indicative of what it does, and what it does is effectively the same as inArray. I can only answer that I started using inArray because Internet Explorer didn’t support indexOf and I wanted my code to work in IE.
That’s not a great answer, I know, because Dr. Twoot is Mac-only—it’s a Fluid SSB—and indexOf works just fine on Macs. I can only say feebly that’s another mental block of mine. I need some kind of druid dude to lift the veil.