← JavaScript

Arrays & Objects

What is destructuring and how is it used with arrays and objects?

Show answer — try answering out loud first

Destructuring is a syntax for extracting values from arrays or objects and assigning them to variables in a single line. With arrays it is based on position; with objects, on the property name.

Instead of accessing values one by one, destructuring lets you "unpack" several at once.

  • With arrays: you extract by position.
  • With objects: you extract by property name.

You can also define default values (used when the value doesn't exist) and rename variables when unpacking objects.

// Array destructuring (by position)
const colores = ["rojo", "verde", "azul"];
const [primero, segundo] = colores;
console.log(primero); // "rojo"
console.log(segundo); // "verde"

// Skip positions with a comma
const [, , tercero] = colores;
console.log(tercero); // "azul"

// Object destructuring (by name)
const usuario = { nombre: "Mike", edad: 30 };
const { nombre, edad } = usuario;
console.log(nombre, edad); // "Mike" 30

// Default values
const { activo = true } = usuario;
console.log(activo); // true (it didn't exist, so it uses the default value)

// Rename variables
const { nombre: nombreUsuario } = usuario;
console.log(nombreUsuario); // "Mike"

// Very useful in function parameters
function saludar({ nombre, edad }) {
  console.log(`${nombre} tiene ${edad} años`);
}
saludar(usuario); // "Mike tiene 30 años"
  • Confusing what matters: with arrays position matters, with objects the exact property name matters.
  • Trying to destructure from null or undefined, which throws an error. For example, const { x } = null throws an error.

"Destructuring lets me pull values out of arrays or objects in a single line. With arrays I extract by position, and with objects by property name. I can also define default values and rename variables. I use it a lot in function parameters to receive an options object cleanly, instead of accessing each property separately."

Quick challenge

Using destructuring, swap the values of two variables a = 1 and b = 2 without using a temporary variable.

See answer
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1