Search code examples
javascriptdestructuringobject-destructuringfalsy

Why destructuring assignment doesn't know null value as falsy and use default value?


Assume we have a function that use some keys in the inner object of argument:

const api = ({ data: { name } = {} }) =>
  `My name is ${name}.`;

If we pass {}, { data: '' }, { data: 0 }, { data: NaN } or { data: undefined } to the function we will see:

'My name is undefined.'

And won't see any error, because destructuring assignment sees the data is falsy and use = {} instead then the name will be undefined.

Question: Why destructuring assignment return error when we pass null to data key?

api({ data: null });

// ==> Uncaught TypeError: Cannot destructure property 'name' of '{}' as it is null.

Solution

  • According to MDN docs concerning default values in object destructuring:

    A variable can be assigned a default, in the case that the value pulled from the object is undefined.