js get object property from null in javascript

To access an object property and avoid an error in case the object is null, you can use the optional chaining operator ?.. Here's an example:

index.tsx
const myObj = null;
const myPropValue = myObj?.myPropName;
console.log(myPropValue); // will output undefined instead of throwing an error
139 chars
4 lines

This code checks whether myObj is null before trying to access myPropName, which prevents an error from occurring. If myObj is indeed null, myPropValue will be assigned the value undefined.

gistlibby LogSnag