Objects & collections
Destructuring
A short way to unpack an object or array into variables.
Why it exists
You often need several fields from an object at once: const name = user.name; const age = user.age; … — repetition that's easy to get wrong. Destructuring says the same in one line: "take name and age out of user". It's especially useful in function parameters and in loops over Object.entries, where each [key, value] pair is unpacked into two names right away.
Where it's used
- Function parameters:
function Card({ title, price }) { … }— that's how React components are written. - Walking pairs:
for (const [key, value] of Object.entries(obj)). - Several results from a function:
const [state, setState] = useState(0). - Taking the parts you need from an API response:
const { data, error } = await res.json().
Syntax
const { key, otherKey } = object;
const { key: variableName = fallback } = object;
const [first, second] = array;Examples
const user = { name: "Anna", age: 30 };
const { name, age } = user;
name; // → "Anna"const order = { id: 7, total: 550 };
const { total, status = "new" } = order;
status; // → "new"const [first, , third] = ["a", "b", "c"];
third; // → "c"const user = { id: 1, name: "Anna", password: "qwerty" };
const { password, ...safe } = user;
safe; // → { id: 1, name: "Anna" }Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Objects are unpacked by name: const { name } = user creates a variable name holding user.name. Order doesn't matter. Rename with a colon: { name: userName }. A default goes after =: { role = "guest" } — used if the property is undefined.
Arrays are unpacked by position: const [a, b] = [1, 2]. Extra items are ignored, missing ones give undefined; skip an item with a comma: const [, second] = list.
...rest gathers "everything else": const { password, ...safe } = user puts every field except the password into safe.
Destructuring works anywhere a variable is created: in const/let, in function parameters and in a for...of header.
Traps
How it differs from…
- Property access with
[] user.namereads one property; destructuring reads several at once and creates variables for them.- Spread
... ... in destructuring gathers the rest into a new object or array; in a literal it spreads it out.
When to pick something else
If you need one property, user.name is simpler than const { name } = user. And don't unpack deeply nested structures in one line like const { a: { b: { c } } } = obj — it's hard to read, and it fails if any level is missing.