get object property from null in javascript

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.tsx
const obj = null;
const value = obj?.property;
console.log(value); // undefined
80 chars
4 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.tsx
const obj = null;
const value = obj ? obj.property : undefined;
console.log(value); // undefined
97 chars
4 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