Script Valley
JavaScript: The Complete Language
Objects, Arrays, and DestructuringLesson 3.3

Destructuring arrays and objects in JavaScript

array destructuring, object destructuring, default values in destructuring, renaming variables, nested destructuring, function parameter destructuring, swap pattern

Destructuring — Unpacking Values

Destructuring is syntax for extracting values from arrays or properties from objects into individual variables. It makes assignment concise and self-documenting.

Array Destructuring

const [first, second, ...rest] = [10, 20, 30, 40];
first  // 10
second // 20
rest   // [30, 40]

// swap without temp variable
let a = 1, b = 2;
[a, b] = [b, a];

// skip elements
const [,, third] = ["x", "y", "z"];
third // "z"

Object Destructuring

const user = { name: "Ana", age: 28, city: "London" };

const { name, age } = user;

// rename
const { name: userName } = user;
userName // "Ana"

// default value
const { role = "viewer" } = user;
role // "viewer" — not in object, default used

Function Parameter Destructuring

function renderUser({ name, role = "viewer", active = true }) {
  return `${name} (${role}) — ${active ? "online" : "offline"}`;
}

renderUser({ name: "Ana", role: "admin" });
// "Ana (admin) — online"

Nested Destructuring

const { address: { city, zip } } = { address: { city: "NYC", zip: "10001" } };
city // "NYC"

Up next

Prototypes and prototype chain in JavaScript

Sign in to track progress