Explain destructuring assignment. Provide examples of object and array destructuring with practical use cases.

3 minintermediatejavascriptes6destructuringassignmentexamplesobject

Quick Answer

Destructuring assignment allows you to extract values from arrays or properties from objects into distinct variables.

Detailed Answer

Explain destructuring assignment. Provide examples of object and array destructuring with practical use cases.

Destructuring assignment allows you to extract values from arrays or properties from objects into distinct variables.

Array Destructuring:

// Basic array destructuring
const colors = ['red', 'green', 'blue'];
const [first, second, third] = colors;
console.log(first); // 'red'
console.log(second); // 'green'
console.log(third); // 'blue'

// Skip elements
const [primary, , tertiary] = colors;
console.log(primary); // 'red'
console.log(tertiary); // 'blue'

// Default values
const [a, b, c, d = 'yellow'] = colors;
console.log(d); // 'yellow'

// Rest operator
const [head, ...tail] = colors;
console.log(head); // 'red'
console.log(tail); // ['green', 'blue']

// Swap variables
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2, 1

Object Destructuring:

const user = {
  id: 1,
  name: 'John Doe',
  email: 'john@example.com',
  address: {
    city: 'New York',
    country: 'USA'
  }
};

// Basic object destructuring
const { name, email, id } = user;
console.log(name); // 'John Doe'

// Rename variables
const { name: userName, email: userEmail } = user;
console.log(userName); // 'John Doe'

// Default values
const { name, age = 25 } = user;
console.log(age); // 25

// Nested destructuring
const { address: { city, country } } = user;
console.log(city); // 'New York'

// Rest operator
const { id, ...userInfo } = user;
console.log(userInfo); // { name: 'John Doe', email: 'john@example.com', address: {...} }

Practical Use Cases:

  1. Function Parameters:
// Instead of passing many parameters
function createUser(name, email, age, city, country) {
  // ...
}

// Use object destructuring
function createUser({ name, email, age = 18, address: { city, country } }) {
  return { name, email, age, city, country };
}

createUser({
  name: 'John',
  email: 'john@example.com',
  address: { city: 'NYC', country: 'USA' }
});
  1. API Response Handling:
async function fetchUser(id) {
  const response = await fetch(`/api/users/${id}`);
  const { data: user, status, message } = await response.json();
  
  if (status === 'success') {
    const { name, email, profile: { avatar, bio } } = user;
    return { name, email, avatar, bio };
  }
  throw new Error(message);
}
  1. React Props:
function UserCard({ user: { name, email, avatar }, onEdit, onDelete }) {
  return (
    <div>
      <img src={avatar} alt={name} />
      <h3>{name}</h3>
      <p>{email}</p>
      <button onClick={onEdit}>Edit</button>
      <button onClick={onDelete}>Delete</button>
    </div>
  );
}
  1. Array Methods:
const users = [
  { id: 1, name: 'John', role: 'admin' },
  { id: 2, name: 'Jane', role: 'user' }
];

// Destructure in map
const userNames = users.map(({ name }) => name);

// Destructure in filter
const admins = users.filter(({ role }) => role === 'admin');