Checking for JavaScript null values
I'm using the Yahoo User Interface API. If I have the following:
var field = yuiDom.get('dobfield');
Is it necessary to check for something like:
if (field == null)
I'm a .NET developer, and whenever I try to get a reference to a control on my web page then I always check for null values. I checked the YUI examples, and references to controls are used extensively, but no where do I see if they check to see if there was a reference.
You might see this:
if(field)
or
if(!field)
Essentially these mean if is null, and if is not null. However, they are equivalent to
if (field == null)
and
if (field != null)
In YUI 2 you could do this:
var lang = YAHOO.util.Lang;
var ctl = YAHOO.util.Dom.get("dobfield");
if (lang.isNull(ctl)) {
alert("Control is null");
} else {
alert("found control");
}
YAHOO.util.Lang is part of the global YAHOO object and it has a bunch of useful cross-browser functions, such as isNull. Since you are using YAHOO.util.Dom, you have Lang by default.
If you are referencing controls that you created and know that will be there, I don't see it as necessary to check for null.
in JavaScript null
values are rarely used, and you won't have a null
value unless you explicitly define it, instead there's undefined
value for non-referenced object, and as Corey Sunwold said, you may see this:
if(obj) {
alert(true); // obj could be (object, not empty string, not null, a not zero number)
} else {
alert(false); // obj could be (undefined, null, '', 0)
}
the previous method does not work with empty objects and empty arrays, you may use jquery isEmptyObject method instead for this case.
精彩评论