To get a property from an object that may be null, you can use optional chaining to safely access the property. If the object is null or undefined, the expression will short-circuit and return undefined instead of throwing an error.
Here is an example:
index.tsx80 chars4 lines
In this example, we try to get the property
of the obj
object using the optional chaining operator (?.
). Since obj
is null, the value
variable will be set to undefined.
Note that the optional chaining operator is relatively new (as of ES2020) and may not be supported in all browsers. In that case, you can use a regular null check with an if statement or the ternary operator:
index.tsx97 chars4 lines
This checks if obj
is truthy before trying to access the property
property. If obj
is falsy (including null and undefined), the expression will short-circuit and return undefined instead of throwing an error.
gistlibby LogSnag