JavaScript nested destructuring

JavaScript nested destructuring:

JavaScript nested destructuring allows you to extract values from nested objects and arrays using a single line of code. This technique is especially useful when working with complex data structures.

How to use nested destructuring:

To use nested destructuring, you start by creating a variable that matches the structure of the object or array you want to extract values from. You can then use the destructuring syntax to extract the values.


    let person = {
      name: 'John Doe',
      age: 30,
      address: {
        street: '123 Main St',
        city: 'Anytown',
        state: 'CA'
      }
    };
    
    let { name, age, address: { city } } = person;
    
    console.log(name); // 'John Doe'
    console.log(age); // 30
    console.log(city); // 'Anytown'
  

Multiple ways to use nested destructuring:

There are multiple ways to use nested destructuring in JavaScript. For example, you can use it with arrays as well as objects:


    let numbers = [1, 2, [3, 4]];
    
    let [a, b, [c, d]] = numbers;
    
    console.log(a); // 1
    console.log(b); // 2
    console.log(c); // 3
    console.log(d); // 4
  

You can also use default values with nested destructuring:


    let person = {
      name: 'John Doe',
      age: 30
    };
    
    let { name, age, address: { city = 'Unknown' } = {} } = person;
    
    console.log(name); // 'John Doe'
    console.log(age); // 30
    console.log(city); // 'Unknown'
  

Overall, JavaScript nested destructuring is a powerful technique that can simplify your code and make it easier to work with complex data structures.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe