JavaScript provides no special syntax for this. You need to test each potentially undefined value before assuming it's defined and trying to access one of its members.
You can still use ||
or &&
for this, but in a non-trivial case, it's probably better to just use an if
.
Using ||
:
var hash = {
a: "one",
b: { cat: "two" }
};
var x = (hash.c || {}).cat
Using &&
:
var x = hash && hash.c && hash.c.cat