3

I try destructuring nested object having null value, but it cause "TypeError: cannot read property 'obj2' of null".

I read about fixing it, but it works on not nested elements.

Take a look at code snippet.

const tmp = { obj: null };

let { obj: { obj2 } = {} } = tmp || {};

I expect destructure object and obj2 to be null or undefined, but it cause error :(

It works good when I have "undefined" instead of "null", but I need case with "null".

3 Answers 3

3

ES6 destructuring default values only work if the attribute is undefined. In any other case it will get the value passed assigned. Even the Javascript falsy values.

A way to circumvent that is to shortcut the possible falsy values, in this case obj that is going to be null.

const tmp = { obj: null };

const { obj } = tmp;

const { obj2 = {} } = obj || {};

console.log(obj);
console.log(obj2);

 

Sign up to request clarification or add additional context in comments.

Comments

0

You won't be able to do that with destructuring. Simply put, like deafult functin parameters, default destructuring values are only applied if the value is undefined, not null or other falsey values.

As an alternative, you could do:

const tmp = { obj: null };
let obj2 = tmp && tmp.obj && tmp.obj.obj2;

Comments

0

Thanks guys @Dez @junvar

I change my code to sth like:

const tmp = { obj: null };
const obj2 = tmp?.obj?.obj2;
console.log(obj2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.