Search code examples
javascriptecmascript-6destructuring

How does nested destructuring work in ES6?


I understand this probably is a pretty basic question, but I'm not proficient with ES6 and I've encountered this syntax:

const { rootStore: { routerStore } } = this.props;

I understand what something like this means:

const { rootStore } = this.props;

(Creating a const rootStore from the property rootStore in this.props).

But what does the above double deconstruction (I assume it's deconstruction) mean?


Solution

  • This is called nested destructuring, and it's very useful in many situations.

    Let's understand it bit by bit.

    Look at this example:

    const person = {
        friend: {
            name: 'john',
            age: 20,
        },
    };
    
    const { friend } = person;
    
    console.log(friend);

    Here we get the value of the prop friend using destructuring. Since the value itself is an object, we can use destructuring with it as well.

    From the previous example:

    const person = {
        friend: {
            name: 'john',
            age: 20,
        },
    };
    
    const { friend } = person;
    
    console.log(friend);
    
    const {age} = friend ;
    
    console.log(age) ; 

    Now we get the age prop using destructuring as well, and that's pretty and super handy, but what if I just need the age prop and I don't need the friend prop? Can I do all the above example in one step? Yes!! and that's the awesomeness of ES6:

    const person = {
        friend: {
            name: 'john',
            age: 20,
        },
    };
    
    const { friend :{age} } = person;
    
    console.log(age); 

    As you can see, we get the value of age in one step, and that's useful in many situations when you have nested objects. In the code above, if you try to log the value of friend you'll get ReferenceError: friend is not defined.

    Did you know? You can make nested destructuring as deep as you want. Look at this complex example which is just for fun.

    const person = {
        friend: {
            name: 'john',
            other: {
                friend: {
                    name: {
                        fullName: {
                            firstName: 'demo',
                        },
                    },
                },
            },
        },
    };
    
    const {
        friend: {
            other: {
                friend: {
                    name: {
                        fullName: { firstName },
                    },
                },
            },
        },
    } = person;
    
    console.log(firstName); // demo

    Pretty!!

    If you want to know more about destructuring take a look at these resources:

    Destructuring assignment MDN

    Destructuring and parameter handling in ECMAScript 6