There are multiple solutions :
Using Optional Chaining, or the "I love new features, or I'm using Babel" method:
Though not supported by all browsers, the optional chaining is the cleanest solution. If you need retro compatibility, you should use Babel or some other transpiler, though.
let organization = undefined
console.log(organization?.name)
organization = {name: "foo"}
console.log(organization?.name)
Using try / catch
, or the "it works or it doesn't" way:
This solution just attempts to show organization.name
, or executes the catch
block if it failed.
let organization = undefined
try {
console.log(organization.name)
} catch(e) {
console.log("organization.name cannot be accessed") // We end up here
}
organization = {name: "foo"}
try {
console.log(organization.name) // We end up here
} catch(e) {
console.log("organization.name cannot be accessed")
}
Using &&
, or the "Working our way to the property" approach:
This one returns the value of organization
if it is falsy (like undefined
, null
, false
,...), or returns organization.name
otherwise.
let organization = undefined
console.log(organization && organization.name) // `organization` is falsy, it will show its value
organization = {name: "foo"}
console.log(organization && organization.name) // `organization` is truthy, it will show `organization.name`