Update in 2020: The nullish-coalescing operator mentioned below is now through the process and in ES2020, as is the optional chaining operator that lets you do:
let postal_code = address?.postal_code;
// −−−−−−−−−−−−−−−−−−−−−−^
With optional chaining, if address
is null
or undefined
, postal_code
will get undefined
as its value. But if address
is neither null
nor undefined
, postal_code
will get the value of address.postal_code
.
JavaScript doesn't have a null-coalescing operator (nor does TypeScript, which mostly limits itself to adding a type layer and adopting features that are reasonably far along the path to making it into JavaScript). There is a proposal for a JavaScript null-coalescing operator, but it's only at Stage 1 of the process.
Using the &&
idiom you've described is a fairly common approach:
let postal_code = address && address.postal_code;
If address
is null
(or any other falsy¹ value), postal_code
will be that same value; otherwise, it will be whatever value address.postal_code
was.
¹ The falsy values are 0
, ""
, NaN
, null
, undefined
, and of course false
.