AmerllicA
AmerllicA

Reputation: 32572

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.

Upvotes: 5

Views: 3013

Answers (1)

Bartek Fryzowicz
Bartek Fryzowicz

Reputation: 6684

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.

Upvotes: 6

Related Questions