There are 3 situations you need to pay attention to:
The attribute does not exist or its value is undefined
;
The attribute exists and its value is null
;
The attribute exists and its value is "falsy" ( false
, 0
, ""
, etc).
The most guaranteed way to differentiate between cases is to use the ===
and !==
operators, since they take the type of the operands into consideration in addition to their values, while ==
and !=
have comparison rules which are not always intuitive.
Some examples:
var obj = { a:"foo", b:"", c:42, d:0, e:true, f:false, g:null, h:undefined };
[].forEach.call("abcdefghi", function(prop) {
document.body.innerHTML += "<p>Testando: " + prop + " (" + obj[prop] + ")</p>";
testa(prop, " === undefined");
testa(prop, " === null");
testa(prop, " === false");
testa(prop, ' === ""');
testa(prop, ' === 0');
testa(prop, " == undefined");
testa(prop, " == null");
testa(prop, " == false");
testa(prop, ' == ""');
testa(prop, ' == 0');
});
function testa(prop, expr) {
if ( eval("obj['" + prop + "'] " + expr) )
document.body.innerHTML += "<p>obj." + prop + " " + expr + "</p>";
}
My suggestion is to list the cases where your condition applies and combine them with &&
, just like you are doing. If it is gambiarra or not, I can not say, but if it is, it is a matter of necessity imposed by the language ...
P.S. You may be wondering: "but how to differentiate between the case where an attribute does not actually exist and the case in which it exists but its value is undefined
?". Well, I'm asking myself the same thing, but I do not remember there being a way to do that.
In case of variables until it gives (see the question "How to verify undefined correctly in Javascript" for more details), but in case of object properties, I'm afraid not to (even converting the object to JSON will cause existing properties but with undefined
to disappear from the result - since JSON does not support undefined
). / p>