So there are questions on S.O. that answer how to check if a property on an object exists. Example Answer is to use Object.prototype.hasOwnProperty()
.
However, how would you check the property of a potentially undefined object?
If one were to attempt to just directly check if a property exists on an undefined object then it would be a reference error.
Semantically, it seems better to check code directly if (obj.prop) //dosomething
-- it shows clearer intent. Is there any way to achieve this? Preferably, is there a built-in Javascript method to do such a thing or by convention?
Motive: A package adds property user.session.email -- but I'm checking to see if email exists, not the session, though the session could be nonexistent.
Update: Many of the answers say to use the && operator to short-circuit. I'm aware that this is a possible solution, but it is not exactly what is desired as it seems like we're working AROUND the JS object syntax -- that is, though you want to really check for a property on an object, you are being forced to check if the object exists in order to do so.
Note to being marked as closed Why was this marked as closed? The link that presumes this is a duplicate may not yield the same answers. We're looking for a better, more semantic solution and marking this closed makes the assumption that "nested" === "potentially undefined".
This question is disputably closed: Since I can't answer my own question now. As of recently, a proposal was put in Stage 1 here that would solve this very issue. Again, the question wants a more semantic solution as is shown in the proposal.