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 by using the operators ===
and !==
, because they take the type of operands into consideration beyond their values, while ==
and !=
have comparison rules that 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’re doing. Whether it’s gambiarra or not, I can’t say, but if it is, it’s a matter of necessity imposed by language...
P.S. You may be wondering: "but how to differentiate between the case where an attribute does not actually exist and the case where it exists but its value is undefined
?". Well, I’m wondering the same thing, but I don’t recall there being a means to it.
In the case of variables it is possible (see question "How to check Undefined correctly in Javascript" for more details), but in the case of object properties, I fear not (even converting the object to JSON will make the existing properties but with value undefined
disappear from the result - because JSON does not support undefined
).
You can do it this way:
if ((json.hasOwnProperty("aviso")) && (json.aviso !== ""))
– Felippe Tadeu