← Back to Chapters

JavaScript Destructuring

? JavaScript Destructuring

? Quick Overview

Destructuring is a JavaScript expression that lets you unpack values from arrays and properties from objects (and other iterables) into distinct variables. It makes code shorter, more readable, and easier to maintain.

?️ Key Concepts

  • Destructuring works with arrays, objects, and any iterable (like Map via iteration).
  • You can extract multiple values in a single statement instead of separate assignments.
  • Object destructuring uses { } and matches property names.
  • Array destructuring uses [ ] and matches by position.
  • You can rename variables, set default values, and destructure nested structures.
  • Map destructuring is often used inside for...of loops.

? Syntax / Theory

? Array Pattern

Array destructuring assigns based on index positions:

Pattern

const [a, b, c] = someArray;

  • a gets index 0, b gets index 1, etc.
  • You can skip elements using commas: const [, second] = arr;

? Object Pattern

Object destructuring assigns based on matching property names:

Pattern

const { prop1, prop2 } = someObject;

  • Variable names must match object keys unless you rename them.
  • You can also provide default values: const { x = 0 } = obj;

? Code Examples

? Array Destructuring

? View Code Example
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;

console.log(first);  // "red"
console.log(second); // "green"
console.log(third);  // "blue"

? Basic Object Destructuring

? View Code Example
const person = {
  name: "Alice",
  age: 25,
  country: "USA"
};

const { name, age } = person;

console.log(name); // "Alice"
console.log(age);  // 25

✏️ Destructuring with Renaming

? View Code Example
const { name: userName, age: userAge } = person;

console.log(userName); // "Alice"
console.log(userAge);  // 25

? Nested Object Destructuring

? View Code Example
const employee = {
  id: 101,
  profile: {
    fullName: "John Doe",
    dept: "Engineering"
  }
};

const {
  profile: { fullName, dept }
} = employee;

console.log(fullName); // "John Doe"
console.log(dept);     // "Engineering"

?️ Map Destructuring via Iteration

? View Code Example
const map = new Map();

map.set("fruit", "apple");
map.set("color", "red");

for (const [key, value] of map) {
  console.log(`${key} => ${value}`);
}

// Output:
// fruit => apple
// color => red

? Live Output / Explanation

? Reading the Console Logs

  • In the array example, [first, second, third] becomes "red", "green", and "blue" based on positions in the colors array.
  • In the object example, { name, age } pulls out the name and age properties from person, so you log "Alice" and 25.
  • With renaming, name: userName means the name property is stored in a variable called userName.
  • In nested destructuring, you drill into employee.profile and directly get fullName and dept.
  • In the Map loop, each iteration gives you a two-element array [key, value], which is destructured into the variables key and value.

? Use Cases / When to Use

  • Unpacking API responses or configuration objects into local variables.
  • Extracting only the needed properties from large objects.
  • Working with arrays returned from functions (e.g., useState in React).
  • Looping over Map entries and directly accessing keys and values.
  • Improving readability in function parameters by destructuring objects directly in the parameter list.

? Tips & Best Practices

  • Use default values to avoid undefined:
    const { age = 18 } = user;
  • You can skip elements in arrays using commas:
    const [, second] = numbers;
  • Map destructuring is commonly done using for...of loops, where each entry is [key, value].
  • Avoid destructuring from null or undefined – it will throw a runtime error. Check or use safe defaults first.
  • Remember: object destructuring matches keys, not order; array destructuring matches order, not names.
  • If you rename properties, keep names meaningful:
    const { fullName: employeeName } = employee.profile;

? Try It Yourself / Practice Tasks

  • Create an array of fruits and destructure the first two elements into variables called firstFruit and secondFruit.
  • Create an object book with properties like title, author, and year. Destructure these inside a function parameter and log them.
  • Create a Map of country–capital pairs and use a for...of loop with destructuring to print them as Country: Capital.
  • Build a nested object (e.g., student.profile.contact.email) and use nested destructuring to extract email in one statement.
  • Practice using default values by destructuring an object that sometimes misses a property (e.g., role = "guest").