Destructuring is a powerful feature introduced in ES6 (ECMAScript 2015) that allows you to “unpack” values from arrays or properties from objects into distinct variables. It makes your code cleaner, more readable, and reduces the need for repetitive index-based or dot-notation access.

1. Object Destructuring

Object destructuring uses the variable name to match the key name in the object.

Basic Example

JavaScript
const person = { name: 'Alice', age: 25, city: 'London' };

// Traditional way
// const name = person.name;
// const age = person.age;

// ES6 Destructuring
const { name, age } = person;

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

Renaming Variables

If you want to use a variable name different from the object key, use a colon :.

JavaScript
const { name: fullName, city: homeTown } = person;

console.log(fullName); // "Alice"

Default Values

You can assign default values in case a property doesn’t exist.

JavaScript
const { country = 'UK' } = person;
console.log(country); // "UK" (since it wasn't in the object)

2. Array Destructuring

Array destructuring is based on the position (index) of the elements.

Basic Example

JavaScript
const colors = ['red', 'green', 'blue'];

// Unpacking by position
const [first, second] = colors;

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

Skipping Elements

Use commas to skip over elements you don’t need.

JavaScript
const [primary, , tertiary] = colors;

console.log(primary);  // "red"
console.log(tertiary); // "blue"

Using the Rest Operator (...)

You can capture the “rest” of the elements into a new array.

JavaScrip
const [head, ...tail] = [1, 2, 3, 4];

console.log(head); // 1
console.log(tail); // [2, 3, 4]

3. Advanced Use Cases

Swapping Variables

Destructuring provides a elegant way to swap values without a temporary temp variable.

JavaScript
let a = 1;
let b = 2;

[a, b] = [b, a];

console.log(a); // 2
console.log(b); // 1

Function Parameter Destructuring

This is extremely common in modern frameworks like React. It allows you to pass an object to a function but only extract what you need.

JavaScript
const user = { id: 101, username: 'jsmith', email: 'j@example.com' };

// Destructuring directly in the parameter list
function displayUser({ username, email }) {
  console.log(`${username}'s email is ${email}`);
}

displayUser(user); // "jsmith's email is j@example.com"

Nested Destructuring

You can even unpack values from objects nested inside other objects or arrays.

JavaScript
const metadata = {
  title: 'My Page',
  config: {
    theme: 'dark',
    version: 1.2
  }
};

const { config: { theme } } = metadata;

console.log(theme); // "dark"

Categorized in:

Javascript ES6,