JavaScriptEasy
What is destructuring?
Destructuring is syntax for unpacking values from arrays (by position) or objects (by property name) into variables, with support for defaults, renaming, nesting and collecting the rest.
Object destructuring
- Basic:
const { name, age } = user. - Rename:
const { name: fullName } = user. - Default:
const { role = "viewer" } = user(applies only when the value isundefined). - Nested:
const { address: { city } } = user. - Rest:
const { password, ...safeUser } = usercopies everything exceptpassword.
Array destructuring
- By position:
const [first, second] = list. - Skip items:
const [, , third] = list. - Rest:
const [head, ...tail] = list. - Swap without a temp variable:
[a, b] = [b, a].
In function parameters
function render({ title, size = "md" }) {} documents the options a function takes and gives defaults in one place. Add = {} as a parameter default so calling with no argument does not throw.
Pitfalls
- Destructuring
nullorundefinedthrows aTypeError. Provide a default (= {}) or use optional chaining before it. - Nested destructuring throws if an intermediate object is missing.
- A statement starting with
{is read as a block; wrap assignments in parentheses:({ a, b } = obj).
Code example
js
1const user = {2 name: "Ada",3 role: undefined,4 password: "secret",5 address: { city: "London", zip: "N1" },6};78const { name: fullName, role = "viewer", address: { city } } = user;9console.log(fullName, role, city); // Ada viewer London1011const { password, ...safeUser } = user; // drop a field12console.log(safeUser); // { name, role, address } - no password1314const [first, , third = "none", ...others] = ["a", "b", undefined, "d", "e"];15console.log(first, third, others); // a none ["d", "e"]1617let a = 1, b = 2;18[a, b] = [b, a]; // swap19console.log(a, b); // 2 12021// Parameters with defaults; `= {}` makes the argument optional22function createButton({ label = "OK", size = "md", disabled = false } = {}) {23 return `${label} (${size}${disabled ? ", disabled" : ""})`;24}25console.log(createButton({ label: "Save", disabled: true })); // Save (md, disabled)26console.log(createButton()); // OK (md)
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.