Codectionary / Developer documentation / JavaScript

Destructuring

Destructuring lets you unpack values from arrays or properties from objects into distinct variables in a single concise statement, instead of accessing each one individually. It works with arrays (by position) and objects (by property name), and can be nested for deeply structured data.

Syntax

const { prop } = object;
const [first, second] = array;

Examples

Object Destructuring

Extracting object properties into variables, including renaming and defaults.

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

const { name, age } = user;
console.log(name, age); // "Alice" 25

// Renaming while destructuring
const { name: userName } = user;
console.log(userName); // "Alice"

// Default values for missing properties
const { country = "Unknown" } = user;
console.log(country); // "Unknown"

Array Destructuring

Extracting array elements by position.

const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first, second); // "red" "green"

// Skipping elements
const [, , third] = colors;
console.log(third); // "blue"

// Swapping variables in one line
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1

Destructuring Function Parameters

A very common pattern - destructuring directly in a function signature.

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

displayUser({ name: "Bob", age: 30, city: "Leeds" });
// city is ignored - only name and age are pulled out

Best practices

  • Use destructuring for function parameters that are objects - it documents exactly what properties the function relies on
  • Provide default values during destructuring instead of separate fallback checks afterward
  • Use nested destructuring sparingly - beyond two levels it often becomes harder to read than explicit access
  • Combine with rest syntax (const { a, ...rest } = obj) to pull out specific properties and keep the remainder together

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation