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
2010-07-14 23:52:04
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
2010-07-14 23:54:20
He asked for a test against null. Not null and undefined.
SimpleCoder
2010-07-14 23:55:32
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
2010-07-14 23:56:59
True, but then he wouldn't just be checking for null ;)
SimpleCoder
2010-07-14 23:58:18
Well the real point is that `==` instead of `===` will work for both `undefined` and `null`.
Pointy
2010-07-14 23:59:17
Yes you are correct.
SimpleCoder
2010-07-15 00:00:56
Agree with Pointy.
Brandon
2010-07-15 00:03:24
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
2010-07-14 23:52:46