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

Is it possible to provide a default value and destructure that value at the same time in Javascript?

Here’s what I mean, I want to do something that is a combination of :

const {b: {c}} = a;

and

const {b={c:0}} = a;

I know I can break them apart like:

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

const a = {};
const {b={c:0}} = a;
const {c} = b;
console.log(c); //will get 0

But is there anyway to do them in a single statement? Something like (below code doesn’t work):

const a = {};
const{b:{c}={c:0}} = a;
console.log(c); // Hoping to get 0

>Solution :

Assuming you want to get a default c value, you could use a nested default value and destructuring.

const
    getC = a => {
        const { b: { c = 0 } = {} } = a;
        return c;
    };

console.log(getC({}));
console.log(getC({ b: {} }));
console.log(getC({ b: { c: 42 } }));
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