Learn JavaScript
❯ objects.destructuring

Destructuring in JavaScript

$concept

Destructuring unpacks values at declaration: const {name, age} = user pulls fields into locals; const [first, second] = pair unpacks arrays positionally. Defaults (const {role = "user"} = ...) and renaming ({name: displayName}) handle absence and collisions, and rest (...rest) collects leftovers.

Function parameters destructure too — ({host, port = 80} = {}) is the options-object idiom — and nested patterns unpack depth in one statement. Overused, destructuring obscures origins; used well, it removes forests of .access chains.

$how it works
1

Unpack objects by name

const {name, age} = user — locals bound from same-named fields.

2

Arrays by position

const [first, second] = pair — order-based unpacking with skippable holes ([, second]).

3

Defaults and renames

{role = "user"} defaults missing; {name: displayName} renames on the way out.

4

Destructure parameters

function f({x, y} = {}) — options objects with per-field defaults at the signature.

$example
let user = { name: "Ada", age: 36 };
let { name, age } = user;
console.log(name, age);
Output
Ada 36
1Both locals bind from same-named fields in one declaration.
2Ada 36 prints — two accesses collapsed into one pattern.
3Missing fields would yield undefined (or defaults, if declared).
$use cases
Pulling needed fields from API responses and props
Options-object parameters with defaults
Swapping and multi-return unpacking ([a, b] = [b, a])
Nested patterns for deep config extraction

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.