The JavaScript destructuring operator
Destructuring unpacks values from arrays or properties from objects into separate variables in a single statement. const { name, age } = user pulls out two properties; const [first, second] = arr pulls out two elements. It makes code shorter and is used constantly with function parameters and imports.
Overview
Destructuring is a tidy syntax for pulling values out of arrays and objects into individual variables. Instead of const name = user.name; const age = user.age;, you write const { name, age } = user and get both at once. With arrays it goes by position: const [first, second] = items grabs the first two elements.
It has several conveniences baked in. You can set defaults for missing values (const { theme = "light" } = opts), rename as you unpack (const { name: userName } = user), and collect the leftovers with the rest pattern (const [head, ...tail] = list). A neat trick falls out of array destructuring: swapping two variables in one line, [a, b] = [b, a], no temporary needed.
Where it really earns its keep is function parameters. Destructuring an options object right in the signature — function create({ title, size = "md" }) — gives you named, self-documenting arguments with defaults. You'll also see it constantly in import statements and when looping with Object.entries(). One note for object destructuring inside existing code: assigning to already-declared variables needs parentheses, ({ a, b } = obj), so the braces aren't read as a block.
Syntax
// object
const { name, age } = user;
const { theme = "light" } = opts; // default
const { name: userName } = user; // rename
// array
const [first, second] = items;
const [head, ...tail] = list; // rest
[a, b] = [b, a]; // swap
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const user = { name: 'Ada', role: 'admin', age: 36 };
const { name, role, country = 'Unknown' } = user;
document.getElementById('out').textContent =
name + ' / ' + role + ' / ' + country; // Ada / admin / Unknown
</script>
Best practices
- Destructure function parameters for named, self-documenting arguments with defaults.
- Provide defaults for properties that might be missing:
const { x = 0 } = obj. - Use the rest pattern to collect remaining items:
const [first, ...rest] = arr. - Wrap object destructuring assignments to existing variables in parentheses:
({ a } = obj).
Frequently asked questions
What is destructuring in JavaScript?
const { a, b } = obj.How do I set a default value when destructuring?
= default after the name: const { size = "md" } = options uses "md" when size is undefined.How do I rename a variable while destructuring?
const { name: userName } = user creates userName from the name property.How do I swap two variables?
[a, b] = [b, a], with no temporary variable.