Given a variable myObj
in Javascript, evaluating myObj.child.name || 'Kid'
will cause an error if myObj.child
does not exist. In comparison, in PHP, $myObj->child->name ?? 'Kid'
would just yield “Kid” with no errors.
One way would be to write the expression let result = (myObj && myObj.child && myObj.child.name) ? myObj.child.name : 'Kid';
.
Another way would be to take advantage of the fact that logical operators in Javascript actually return the value of one of the operands, and simply write let result = (myObj && myObj.child && myObj.child.name) || 'Kid';
.
References:
- Logical Operators – Javascript MDN
- Why don’t logical operators (&& and ||) always return a boolean result?
let a = { x: { y: 2 } }; let result = null; result = (a && a.x && a.x.z); // undefined, not false result = (a && a.x && a.x.y); // 2, not true result = (a && a.b && a.b.c) || 5; // 5 result = (q && a && a.x) || 7; // Uncaught ReferenceError: q is not defined