Destructuring Arrays and Objects
Destructuring lets you extract values from objects and arrays into separate variables with a single clean line of code.
Object destructuring matches by property name. Array destructuring matches by position. You can rename, set defaults, skip elements, and destructure directly in function parameters.
EXERCISE
1Object Destructuring: Pull Values Out in One Line
Destructuring lets you extract properties from an object into separate variables with a single, clean line of code.
Destructuring pulls values out of an object into separate variables in one statement. It replaces a run of lines that each repeat a name twice.
const user = { name: "Sara", age: 28, city: "Dubai" };
const name = user.name;
const age = user.age;
const city = user.city;
Three lines that each say the same thing on both sides of the equals. Repeating a name is exactly the sort of thing that drifts when someone renames a property and misses one.
const { name, age, city } = user;
console.log(name); // "Sara"
console.log(age); // 28
Read the braces on the left as a shape rather than as an object being built. It says: from user, take the properties called name, age and city, and bind each to a variable of the same name. Nothing is constructed and user is not modified.
The matching is by name, not by order:
const { city, name } = user;
console.log(city, name); // "Dubai" "Sara"
Rearranging changes nothing. Asking for a property that does not exist gives undefined rather than an error, exactly as a normal property read would:
const { email } = user;
console.log(email); // undefined
A default covers the missing case:
const { country = "unknown" } = user;
console.log(country); // "unknown"
The default applies only when the property is undefined. A property holding null, 0 or "" is present, so the default does not fire.
Renaming, for when the property name is not the variable name you want:
const { name: userName, city: userCity } = user;
console.log(userName); // "Sara"
The colon reads backwards from an object literal, which catches people: the property is on the left and the new variable name is on the right.
Nested objects use the same shape, one level deeper:
const student = { name: "Ali", address: { city: "London" } };
const { address: { city } } = student;
console.log(city); // "London"
console.log(address); // ReferenceError: address is not defined
That last line is worth knowing. Writing address: { city } uses address as a path, not as a variable, so only city is created.
EXERCISE
2Array Destructuring
Array destructuring works by position instead of by name. The first variable gets the first element, the second gets the second, and so on.
Object destructuring matches by name. Array destructuring matches by position, because that is the only thing an array element has.
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
The names on the left are yours to choose. Nothing connects first to the value "red" except that it is written in the first position.
Skip positions with a bare comma:
const scores = [95, 82, 78, 91];
const [best, , , fourth] = scores;
console.log(best); // 95
console.log(fourth); // 91
Two commas in a row skip an element. It is terse and easy to miscount, so it is worth keeping to one or two.
Missing positions give undefined, and defaults work the same as on objects:
const [a, b, c = "none"] = ["x", "y"];
console.log(c); // "none"
Swapping two variables without a temporary:
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1
The right side is evaluated into a new array first, so both original values are captured before either assignment happens. This is one of the few places the syntax is genuinely shorter and clearer than the alternative.
Collecting the rest of the elements:
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2, 3, 4]
...tail gathers everything remaining into a new array. It has to come last, because there is no meaningful "everything else" in the middle.
Returning several values from a function:
function minMax(numbers) {
return [Math.min(...numbers), Math.max(...numbers)];
}
const [low, high] = minMax([5, 2, 8, 1]);
console.log(low, high); // 1 8
A function can only return one value, and an array with destructuring at the call site is the lightest way to return two. This is exactly the pattern behind useState in , where const [value, setValue] = useState(0) is array destructuring and nothing more.
EXERCISE
3Destructuring in Function Parameters
You can destructure directly in function parameters. Instead of passing an entire object and picking it apart inside, you extract what you need right in the parameter list.
Destructuring works in a parameter list, which is where it changes how functions are called rather than just shortening a line.
function greet({ name, city }) {
return name + " from " + city;
}
console.log(greet({ name: "Sara", city: "Dubai" })); // "Sara from Dubai"
The function takes one object and names the parts it needs. Compare that with the positional version:
function greet(name, age, city, country, isActive) {
return name + " from " + city;
}
greet("Sara", 28, "Dubai", "UAE", true);
At the call site, every argument is a value with no label. Getting two of them the wrong way round is silent if they are the same type, and adding a parameter in the middle means finding every call. With an object, each value is named where it is passed and the order does not matter.
Defaults go in the pattern:
function connect({ host, port = 5432, secure = true }) {
return host + ":" + port + (secure ? " (tls)" : "");
}
console.log(connect({ host: "db.local" })); // "db.local:5432 (tls)"
The defaults live in the signature, so the function's expectations are visible without reading the body.
Calling with nothing needs a default for the whole parameter:
function connect({ host = "localhost", port = 5432 } = {}) {
return host + ":" + port;
}
console.log(connect()); // "localhost:5432"
Without the trailing = {}, calling connect() tries to destructure undefined and throws. That one is easy to miss, because the function looks like it has defaults for everything.
The same works on arrays, which is how you take apart a pair:
function distance([x1, y1], [x2, y2]) {
return Math.hypot(x2 - x1, y2 - y1);
}
console.log(distance([0, 0], [3, 4])); // 5
Rest collects whatever you did not name:
function render({ id, ...attributes }) {
return { id, count: Object.keys(attributes).length };
}
console.log(render({ id: 1, color: "red", size: "lg" })); // { id: 1, count: 2 }
This is the standard way to pull one value out of a configuration object and pass everything else along untouched.
Pro Tip: Once a function has more than two parameters, or any boolean parameter, an options object is usually the better signature.
save(data, true, false)tells the reader nothing;save(data, { overwrite: true, backup: false })tells them everything.
