[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?