Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is reading properties of null undefined sometimes but other times throws an error?

Example 1: When res is null, coords is undefined.

const res = await Geolocation.getGeolocation();
const { coords } = res || {};

Example 2: When res is null, I get TypeError: Cannot read properties of null (reading 'points')

const res = await API.getPoints(
          latitude,
          longitude,
          market,
        );
const { points } = res;

Example 2 comes right after Example 1 in my code, why would the behavior be different?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The difference between

const { coords } = res || {};

and

const { points } = res;

is the || {} part. It makes makes the entire right side of the expression to equal {} if res is falsy therefore doing {coords} = {} is allowed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading