Advanced25 min read

Destructuring

Learn to unpack values from arrays and properties from objects into distinct variables using destructuring assignment.

Array Destructuring

Destructuring lets you unpack values from arrays (or properties from objects) into individual variables in a single statement.

Basic array destructuring:

javascript
const [a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

Skipping values — use commas without variable names:

javascript
const [, second, , fourth] = [10, 20, 30, 40];
console.log(second); // 20
console.log(fourth); // 40

Default values — provide fallbacks for missing elements:

javascript
const [a = 0, b = 0, c = 0] = [1, 2];
console.log(c); // 0 (default, since the array has no third element)

Rest element — collect remaining items into a new array:

javascript
const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest);  // [2, 3, 4, 5]

Swapping variables — a classic trick:

javascript
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x); // 2
console.log(y); // 1

Object Destructuring

Object destructuring extracts properties by their name:

javascript
const person = { name: 'Alice', age: 30, city: 'Paris' };
const { name, age } = person;
console.log(name); // 'Alice'
console.log(age);  // 30

Renaming variables — use a colon to assign to a different variable name:

javascript
const { name: fullName, age: years } = person;
console.log(fullName); // 'Alice'
console.log(years);    // 30

Default values:

javascript
const { name, role = 'user' } = { name: 'Bob' };
console.log(role); // 'user' (default, since role is not in the object)

Nested destructuring — extract from nested objects:

javascript
const user = {
  name: 'Alice',
  address: {
    city: 'Paris',
    country: 'France'
  }
};

const { address: { city, country } } = user;
console.log(city);    // 'Paris'
console.log(country); // 'France'

You can combine renaming, defaults, and nesting as needed.

Destructuring in Functions

One of the most powerful uses of destructuring is in function parameters. Instead of accepting an object and accessing its properties inside the function body, you can destructure right in the parameter list.

Without destructuring:

javascript
function greet(person) {
  console.log('Hello, ' + person.name + '! Age: ' + person.age);
}

With destructuring:

javascript
function greet({ name, age }) {
  console.log('Hello, ' + name + '! Age: ' + age);
}

greet({ name: 'Alice', age: 30 }); // Hello, Alice! Age: 30

With default values:

javascript
function createUser({ name = 'Anonymous', role = 'user' } = {}) {
  return { name, role };
}

createUser({ name: 'Bob' });  // { name: 'Bob', role: 'user' }
createUser();                  // { name: 'Anonymous', role: 'user' }

The = {} at the end provides a default empty object so the function can be called with no arguments at all.

This pattern is extremely common in modern JavaScript, especially for functions that accept configuration objects with many optional properties. It makes the function signature self-documenting.

Destructuring Examples

html
<div id="output"></div>

<script>
  // Array destructuring
  const colors = ['red', 'green', 'blue', 'yellow'];
  const [primary, secondary, ...others] = colors;

  // Object destructuring
  const book = {
    title: 'JavaScript Guide',
    author: 'MDN',
    year: 2024,
    tags: ['programming', 'web']
  };
  const { title, author, year, tags: [firstTag] } = book;

  // Function parameter destructuring
  const describe = ({ title, author }) => `${title} by ${author}`;

  const output = document.getElementById('output');
  output.innerHTML = `
    <p>Primary: ${primary}, Secondary: ${secondary}</p>
    <p>Others: [${others}]</p>
    <p>Book: ${title} (${year})</p>
    <p>Author: ${author}</p>
    <p>First tag: ${firstTag}</p>
    <p>Description: ${describe(book)}</p>
  `;
</script>

What does `const { x: a } = { x: 10 }` assign to `a`?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.