Nested destructuring with undefined values in JavaScript

Let's assume that we have the following 2 objects:

jsx
const person_A = {
    name: 'Erik',
    age: 29,
    tasks: {
        current: {
            name: 'Writing code',
            ini: '18:16',
        },
        previous: {
            name: 'Cooking',
            ini: '14:05',
            end: '15:25'
        } 
    }
}

const person_B = {
    name: 'Andrea',
    age: 26
}

Destructure person_A

We could destructure person_A as:

jsx
const { name, age, tasks } = person_A;

console.log(name, age, tasks);
// Erik, 29, {current{...}, previous{...}}

To do a nested destructure (double destructure):

jsx
const { name, age, tasks: { current, previous } } = person_A;

console.log(name, age, current, previous);
// Erik, 29, {name: 'Writing code', ini: '18:16'}, {name: 'Cooking', ini: '14:05', end: '15:25'}

Destructure person_B

Now, if we do the same with person_B:

jsx
const { name, age, tasks } = person_B;

console.log(name, age, tasks);
// Andrea, 26, undefined

We get an error doing a nested destructure:

jsx
const { name, age, tasks: { current, previous } } = person_B;

console.log(name, age, current, previous);
// Cannot read property 'current' of undefined

To avoid the undefined values, we could assign an inital value to them.

jsx
const { 
    name, 
    age, 
    tasks: { 
        current  = { name: 'Something' }, 
        previous = { name: 'Something else' } 
    } = {} 
} = person_B;

console.log(name, age, current, previous);
// Andrea, 26, {name: 'Something'}, {name: 'Something else'}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.