Destructuring

Destructuring is a convenient way to unpack values from arrays or properties from objects into separate variables. Instead of accessing each item one by one, you can grab multiple values in a single line.

It was introduced in ES6 and makes your code shorter and easier to read.

javascript

// Without destructuring
const colors = ["red", "green", "blue"];
const first = colors[0];
const second = colors[1];

// With destructuring
const [a, b, c] = colors;
console.log(a); // red
console.log(b); // green
console.log(c); // blue

One handy use of array destructuring is swapping (reversing) two variables. Normally you would need a temporary variable, but with destructuring you can do it in one line.

javascript

let x = 10;
let y = 20;

// Swap values using destructuring
[x, y] = [y, x];

console.log(x); // 20
console.log(y); // 10

No temporary variable needed. The right side creates a temporary array [y, x], and the left side unpacks it back into x and y in reversed order.

A function can only return one value, but you can return an array and then destructure it to get multiple values out of it.

javascript

function minMax(arr) {
  return [Math.min(...arr), Math.max(...arr)];
}

const [min, max] = minMax([3, 1, 7, 2, 9]);
console.log(min); // 1
console.log(max); // 9

The function returns an array with two values. Using destructuring, you capture both values directly into named variables in one step.

When an array contains another array inside it (nested array), you can destructure the inner array too by using nested brackets in the pattern.

javascript

const nested = [1, [2, 3], 4];

const [first, [second, third], fourth] = nested;

console.log(first);  // 1
console.log(second); // 2
console.log(third);  // 3
console.log(fourth); // 4

The inner brackets [second, third] match the nested array [2, 3] and extract its values individually.

If the array has fewer items than the variables you are destructuring into, the missing ones will be undefined. You can avoid this by assigning default values.

javascript

const [p = 1, q = 2, r = 3] = [10, 20];

console.log(p); // 10  (value from array)
console.log(q); // 20  (value from array)
console.log(r); // 3   (default used, no value in array)

Default values are only used when the corresponding position in the array is undefined. If a value exists, the default is ignored.

Just like arrays, you can destructure objects. Instead of square brackets [], you use curly braces {}. The variable names must match the property names of the object.

javascript

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

const { name, age, city } = person;

console.log(name); // Alice
console.log(age);  // 25
console.log(city); // London

With object destructuring, the order does not matter. What matters is that the variable name matches the property name.

You do not have to extract all properties. You can pick only the ones you need. The rest of the object is simply ignored.

javascript

const car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2022,
  color: "white"
};

// Extract only brand and year
const { brand, year } = car;

console.log(brand); // Toyota
console.log(year);  // 2022

Only brand and year are extracted. The model and color properties are left in the original object but not assigned to any variable.

Sometimes you want to store the value under a different variable name. You can do this using a colon : to rename the variable during destructuring.

javascript

const user = {
  firstName: "Bob",
  age: 30
};

// Rename firstName to name, age to userAge
const { firstName: name, age: userAge } = user;

console.log(name);    // Bob
console.log(userAge); // 30

The syntax is propertyName: newVariableName. Here firstName is the property in the object, and name is the new variable that holds its value.

You can also combine renaming with default values:

javascript

const { firstName: name = "Guest", age: userAge = 18 } = {};

console.log(name);    // Guest
console.log(userAge); // 18

When an object has another object inside it, you can destructure the inner object too by nesting the curly braces in the pattern.

javascript

const employee = {
  name: "Sara",
  address: {
    city: "Paris",
    zip: "75001"
  }
};

const { name, address: { city, zip } } = employee;

console.log(name); // Sara
console.log(city); // Paris
console.log(zip);  // 75001

Note that address itself is not created as a variable here. Only city and zip are extracted from the nested object.

You can use destructuring directly in a function's parameter list. This is very common when a function receives an object as an argument. Instead of accessing properties one by one inside the function, you extract them right in the parameter.

javascript

function greet({ name, age }) {
  console.log(`Hello, ${name}! You are ${age} years old.`);
}

const user = { name: "Tom", age: 28 };
greet(user);
// Output: Hello, Tom! You are 28 years old.

You can also use it with arrays in function parameters:

javascript

function showCoords([x, y]) {
  console.log(`x: ${x}, y: ${y}`);
}

showCoords([5, 10]);
// Output: x: 5, y: 10

Destructuring in function parameters makes your code cleaner and removes the need for extra lines inside the function body.

  • Destructuring lets you unpack values from arrays or objects into variables in a single step.
  • Use [] for array destructuring and {} for object destructuring.
  • You can swap variables using array destructuring without a temporary variable.
  • Functions can return an array and you can destructure it to get multiple values.
  • Nested destructuring lets you reach inside nested arrays or objects.
  • Default values are used when a position or property is undefined.
  • You can rename a property during object destructuring using propertyName: newName.
  • Destructuring works directly in function parameters, making code cleaner.