Beginner LevelJavaScript & TypeScript
How does destructuring assignment work for objects and arrays in JavaScript?
❓ Interview Prompt: Explain object and array destructuring, default values, renaming properties, and nested destructuring.
Destructuring extracts values from arrays or properties from objects into distinct variables with a clean syntax:
Object Destructuring:
Extracts by property name:
•
Default values:
const { role = 'user' } = person;•
Renaming:
const { name: userName } = person;•
Nested:
const { location: { city } } = person;Array Destructuring:
Extracts by position / index:
•
Skipping items:
const [first, , third] = items;•
Rest pattern:
const [head, ...tail] = numbers;•
Variable swapping:
[a, b] = [b, a];Code Implementation Example
javascript
const user = { name: 'Alice', age: 30, location: { city: 'NYC' } };
// Object destructuring with renaming and default
const { name: fullName, role = 'Member', location: { city } } = user;
console.log(fullName, role, city); // "Alice" "Member" "NYC"
// Array destructuring with rest operator
const colors = ['red', 'green', 'blue', 'yellow'];
const [primary, secondary, ...others] = colors;
console.log(primary, secondary, others); // "red" "green" ["blue", "yellow"]
// Easy variable swap without temp variable
let x = 1, y = 2;
[x, y] = [y, x]; // x is 2, y is 1💡Object property renaming, default values, nested destructuring, and array rest extraction.
🎯 Interview Key Takeaway
Object destructuring matches keys by name; array destructuring matches items by position. Both support default values.
#Destructuring#Objects#Arrays#Beginner
Back to all JavaScript & TypeScript Questions→