Level: Intermediate | Player: 08_string
Learning Objectives
- Only necessary values can be taken out as variables from objects and arrays.
- Default values and aliases (rename) can be used.
- Bind the rest with rest(
...). - Spread and merge or copy with spread(
...). - Use structural decomposition in function parameters.
1. Object structure decomposition
The value is retrieved from the object into a variable with the same name as the key name at once.
const user = { id: 1, name: "Minji", age: 21 };
const { name, age } = user;
const { id: userId } = user; //alias
const { email = "none" } = user; //default
2. Array decomposition
Arrays are retrieved based on location.
const [a, b, c] = [10, 20, 30];
const [first, , third] = [1, 2, 3]; //omit the second
const [x = 0, y = 0] = [5]; // y = 0
3. rest parameters
Collect the rest from as-array/object.
const [head, ...tail] = [1, 2, 3, 4]; // head=1, tail=[2,3,4]
const { name, ...rest } = user; //rest means everything except name
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
4. spread
array/object Spread, combine or shallow copy.
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b]; // [1,2,3,4]
const base = { x: 1, y: 2 };
const extended = { ...base, z: 3 }; // { x:1, y:2, z:3 }
If the object spread has the same key, the latter wins.
Core example
| file | Contents covered |
|---|---|
01_object_destructure.js |
object destructuring + default |
02_array_destructure.js |
array destructuring + swap |
03_rest.js |
rest parameters |
04_spread.js |
array/object spread |
⚠️ Common Mistakes
const { name, age } = undefined→ TypeError. Handles= {}by default.- Forgetting that spread is a shallow copy (nested objects share references).
- Rest should always come last.
- When disassembling an object, the alias syntax
key: aliasis misunderstood as a type notation. - In array decomposition, variables are misaligned due to incorrect counting of positions.
❓ Frequently Asked Questions (FAQ)
Q1. Difference between spread and Object.assign? A. The result is almost the same, but spread is more concise and returns a new object.
Q2. Array deep copy? A. Use structuredClone(arr) or JSON bypass.
Q3. When is it good to destructure into function arguments? A. Readability improves when there are many option objects.