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

Time:10-22

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?

CodePudding user response:

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.

  • Related