Destructuring
Destructuring lets you unpack values from arrays and objects into named variables in a single, readable expression. It eliminates repetitive property access code and is one of the most widely-used ES6 features.
What is destructuring in JavaScript?
Destructuring unpacks values from arrays or properties from objects into variables in one line. const { name, age } = user; creates name and age from the object, and const [first, second] = list; takes the first two array items. You can rename, set defaults and destructure function parameters directly.
const { name, role = "student", address: { city } } = user;
const { name: userName } = user; // rename
const [first, , third, ...rest] = [1, 2, 3, 4, 5];
[a, b] = [b, a]; // swap
function show({ title, done = false }) { … } // parameter destructuringArray Destructuring
Object Destructuring
Destructuring in Function Parameters
Instead of accessing options.timeout inside the function, destructure right in the parameter list. This makes the expected shape of the argument explicit and provides defaults.
Without destructuring
With destructuring
Tip: When destructuring in function parameters, provide a default for the whole parameter to handle the case when it is called with no argument: function f({ x = 0 } = {}) {}
Common Pitfalls
Interactive Examples
Code Editor
<pre id="out"></pre>Preview
Destructuring — step by step
Array destructuring — position-based
const [a, b, c] = [1, 2, 3] unpacks by position. You can skip elements with empty commas: const [first, , third] = arr. Use rest syntax to capture the remainder: const [head, ...tail] = arr. Default values fill in when the value is undefined: const [x = 0] = [].
🎯 Quick Check
What does const { x = 10 } = {} produce for x?
JavaScript Destructuring: summary
Key points
- Defaults apply only when the value is
undefined, notnull. - Destructuring a property of
undefinedthrows; give nested objects a default ({ address = {} }). - Rest (
...rest) collects the remaining items or properties.
Frequently asked questions
›How do I destructure with a default value?
Add = value after the name: const { theme = "light" } = settings;.