2 min read

Destructuring

Destructuring assignment is a special syntax introduced in ES6 that allows you to "unpack" values from arrays, or properties from objects, into distinct variables.

1. Array Destructuring

You can extract values from an array and assign them to variables based on their position.

const numbers = [1, 2, 3];
const [a, b, c] = numbers;

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

Skipping Items

You can skip items using commas.

const [first, , third] = [1, 2, 3];
console.log(first); // 1
console.log(third); // 3

Rest Operator

You can capture the remaining items in an array.

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

2. Object Destructuring

You can extract properties from an object and assign them to variables with the same name.

const person = { name: "Alice", age: 25 };
const { name, age } = person;

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

Renaming Variables

If you want to assign a property to a variable with a different name, use a colon.

const { name: fullName, age: years } = person;

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

Default Values

You can assign default values for properties that might be undefined.

const { name, isAdmin = false } = person;
console.log(isAdmin); // false

3. Nested Destructuring

You can destructure nested objects and arrays.

const user = {
  id: 1,
  details: {
    email: "test@example.com",
    address: { city: "New York" }
  }
};

const { details: { address: { city } } } = user;
console.log(city); // "New York"

4. Function Parameter Destructuring

This is extremely useful for functions that take configuration objects.

function printUser({ name, age }) {
  console.log(`${name} is ${age} years old.`);
}

const user = { name: "Bob", age: 30, email: "bob@example.com" };
printUser(user); // "Bob is 30 years old."

programming/javascript/vanilla/javascript programming/javascript/vanilla/es6-features