views:

43

answers:

3

I'm looping through an array in JavaScript to check for null in each object using jQuery, what would be the best cross browser solution for this?

+1  A: 

What's wrong with this:

if (myValue === null)
{
    \\ Null
}

Null is a reserved keyword in JavaScript, and it shouldn't change across browsers.

SimpleCoder
Trick there is that "undefined" is not `===` to `null`. If there are "holes" in an array because nothing's ever put *anything* there, then a reference to that element will be `undefined`, not `null`.
Pointy
He asked for a test against null. Not null and undefined.
SimpleCoder
True, @SimpleCoder, he did, but if you're checking an array for empty cells there's a chance that the distinction would be important.
Pointy
True, but then he wouldn't just be checking for null ;)
SimpleCoder
Well the real point is that `==` instead of `===` will work for both `undefined` and `null`.
Pointy
Yes you are correct.
SimpleCoder
Agree with Pointy.
Brandon
A: 

null is pretty reliably null. If you don't care specifically about null - that is, if you'd do the same thing when something is undefined as you would when it's null or any other "falsy" value, you can just use

if (!array[i]) { /* nothing there */ }

However that's not safe if you're data is numeric, because zero is "falsy", or if they're strings where an empty string should not count as "empty" in the array, for the same reason. Thus you can compare with the double-equals comparator to null

if (array[i] == null) { /* nothing there */ }

I've never heard of any cross-browser issues with this.

Pointy
this headed me to the right direction.. the problem I had was doing $(arrayname).each, instead of $.each(arrayname, function()).... doing the later worked for IE, FF.
Brandon
Yes that'd certainly be a problem :-)
Pointy
A: 

(obj == null) is pretty damn cross browser last time I checked.

Igor Zevaka