Destructuring Recap

Destructuring is a concise way to extract values from arrays or properties from objects into distinct variables. It improves code readability and reduces repetition.

Illustration of destructuring_recap
Illustration of destructuring_recap

💡 Core Concept

Use curly braces {} for object destructuring and square brackets [] for array destructuring.

Object Destructuring

Extract properties by matching variable names to object keys:

📌 Deep Dive: Basic Object Destructuring

JAVASCRIPT
const person = { name: 'Alice', age: 30 };
const { name, age } = person;
console.log(name, age);
Output
Alice 30

You can rename variables during destructuring:

📌 Deep Dive: Renaming Variables

JAVASCRIPT
const { name: firstName, age: years } = person;
console.log(firstName, years);
Output
Alice 30

Array Destructuring

Assign variables based on position in the array:

📌 Deep Dive: Basic Array Destructuring

JAVASCRIPT
const colors = ['red', 'green', 'blue'];
const [first, second] = colors;
console.log(first, second);
Output
red green

Skip unwanted items using commas:

📌 Deep Dive: Skipping Items in Array

JAVASCRIPT
const [ , , third] = colors;
console.log(third);
Output
blue

Default Values

Provide defaults to avoid undefined when the value is missing:

📌 Deep Dive: Default Values

JAVASCRIPT
const { name, city = 'Unknown' } = { name: 'Bob' };
console.log(name, city);
Output
Bob Unknown

Nested Destructuring

Extract values from nested objects or arrays:

📌 Deep Dive: Nested Object Destructuring

JAVASCRIPT
const user = {
  id: 1,
  profile: { username: 'jdoe', email: 'jdoe@example.com' }
};
const { profile: { username, email } } = user;
console.log(username, email);
Output
jdoe jdoe@example.com

⚠️ Important

When destructuring objects, variable names must match property names unless renamed explicitly. Array destructuring depends on item order, not names.

Object vs Array Destructuring
FeatureObjectArray
SyntaxCurly braces {}Square brackets []
MatchingBy property nameBy position
RenamingAllowed with property: variableNot applicable
Default valuesSupportedSupported
Skipping valuesUse partial destructuringUse commas ,

💡 Quick Tip

Destructuring works well in function parameters, variable assignment, and extracting data from API responses.