#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 50 of 50medium

What are advanced Destructuring patterns?

Understanding complex destructuring scenarios.

What You'll Learn

  • Nested destructuring
  • Mixed patterns
  • Function parameter destructuring

Nested Destructuring

code.jsJavaScript
const data = {
  user: {
    name: 'John',
    address: {
      city: 'NYC',
      zip: '10001'
    }
  }
};

// Deep destructuring
const {
  user: {
    name,
    address: { city }
  }
} = data;

console.log(name); // 'John'
console.log(city); // 'NYC'

Array in Object

code.jsJavaScript
const response = {
  status: 200,
  data: ['apple', 'banana', 'cherry']
};

const {
  status,
  data: [first, second]
} = response;

console.log(first);  // 'apple'
console.log(second); // 'banana'

Object in Array

code.jsJavaScript
const users = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' }
];

const [{ name: firstName }, { name: secondName }] = users;
console.log(firstName);  // 'John'
console.log(secondName); // 'Jane'

Function Parameters

code.jsJavaScript
// Object destructuring with defaults
function createUser({
  name,
  age = 18,
  role = 'user'
} = {}) {
  return { name, age, role };
}

createUser({ name: 'John' });
// { name: 'John', age: 18, role: 'user' }

// Array destructuring
function getCoords([x, y, z = 0]) {
  return { x, y, z };
}

getCoords([10, 20]); // { x: 10, y: 20, z: 0 }

Swapping Variables

code.jsJavaScript
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2, 1