[Bounty Edit]
I'm looking for a good explanation when you should set/use null
or undefined
and where you need to check for it. Basically what are common practices for these two and is really possible to treat them separately in generic maintainable codee?
When can I safely check for === null
, safely check for === undefined
and when do I need to check for both with == null
When should you use the keyword undefined
and when should one use the keyword null
I have various checks in the format of
if (someObj == null)
or if (someObj != null)
which check for both null and undefined. I would like to change all these to either === undefined
or === null
but I'm not sure how to guarantee that it will only ever be one of the two but not both.
Where should you use checks for null
and where should you use checks for undefined
A concrete example:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 0; i < List.length; i++) {
if (List[i] == null) continue;
if (id === List[i].getId()) {
return List[i];
}
}
return null;
}
var deleteObject = function(id) {
var index = getIndex(id) // pretty obvouis function
// List[index] = null; // should I set it to null?
delete List[index]; // should I set it to undefined?
}
This is just one example of where I can use both null
or undefined
and I don't know which is correct.
Are there any cases where you must check for both null
and undefined
because you have no choice?
When to set/use them...
Note that a method without a return statement returns undefined, you shouldn't force this as an expected response, if you use it in a method that should always return a value, then it should represent an error state internally.
Use null for an intentional or non-match response.
As for how/when to check...
undefined, null, 0, an empty string, NaN and false will be FALSE via coercion. These are known as "falsy" values... everything else is true.
Your best bet is coercion then testing for valid exception values...
Numeric testing is the real bugger, since true, false and null can be coerced into a number, and 0 coerces to false.
Some DOM methods return
null
. All properties of an object that have not been set returnundefined
when you attempt to access them, including properties of anArray
. A function with noreturn
statement implicitly returnsundefined
.I would suggest making sure you know exactly what values are possible for the variable or property you're testing and testing for these values explicitly and with confidence. For testing null, use
foo === null
. For testing forundefined
, I would recommend usingtypeof foo == "undefined"
in most situations, becauseundefined
(unlikenull
) is not a reserved word and is instead a simple property of the global object that may be altered, and also for other reasons I wrote about recently here: variable === undefined vs. typeof variable === "undefined"I think it's interesting to note that, when Windows was first written, it didn't do a lot of checks for invalid/NULL pointers. Afterall, no programmer would be dumb enough to pass NULL where a valid string was needed. And testing for NULL just makes the code larger and slower.
The result was that many UAEs were due to errors in client programs, but all the heat went to Microsoft. Since then, Microsoft has changed Windows to pretty much check every argument for NULL.
I think the lesson is that, unless you are really sure an argument will always be valid, it's probably worth verifying that it is. Of course, Windows is used by a lot of programmers while your function may only be used by you. So that certainly factors in regarding how likely an invalid argument is.
In languages like C and C++, you can use ASSERTs and I use them ALL the time when using these languages. These are statements that verify certain conditions that you never expect to happen. During debugging, you can test that, in fact, they never do. Then when you do a release build these statements are not included in the compiled code. In some ways, this seems like the best of both worlds to me.
Functions implicitly return
undefined
. Undefined keys in arrays areundefined
. Undefined attributes in objects areundefined
.document.getElementById
returnsnull
if no elements are found.You should never have to check for
undefined
ornull
(unless you're aggregating data from both a source that may return null, and a source which may return undefined).I recommend you avoid
null
; useundefined
.I would treat them as 2 completely different values, and check for the one you know might occur.
If you're checking to see if something has been given a value yet, check against
undefined
.If you're checking to see if the value is 'nothing,' check against 'null'
A slightly contrived example:
Say you have a series of ajax requests, and you're morally opposed to using callbacks so you have a timeout running that checks for their completion.
Your check would look something like this:
tldr; They are two different values,
undefined
means no value has been given,null
means a value has been given, but the value is 'nothing'.If you call a function with no explicit return then it implicitly returns undefined. So if I have a function that needs to say that it did its task and there is nothing result, e.g. a XMLHTTPRequest that returned nothing when you normally expect that there would be something (like a database call), then I would explicitly return null.