Cleanly extract data from objects and arrays, then copy and merge structures with the spread operator.
Open this lesson in KodokonWhen you receive data from an API, you often only need a few properties. Destructuring extracts them in one line, with the option to rename, reach into nested objects, and provide a default value if the property is missing.
const user = {
id: 42,
name: "Lea",
address: { city: "Lyon", zip: "69001" }
};
const { name, address: { city } } = user;
const { role = "guest" } = user;
console.log(name, city, role); // "Lea" "Lyon" "guest"Destructuring also works on arrays, this time by position. Its most professional use remains function parameters: instead of receiving an opaque object, the signature announces exactly which properties are expected. The code becomes self-documenting.
const podium = ["gold", "silver", "bronze"];
const [first, , third] = podium;
console.log(first, third); // "gold" "bronze"
function formatUser({ name, role = "guest" }) {
return `${name} (${role})`;
}
console.log(formatUser({ name: "Sam" }));
// "Sam (guest)"The same ... operator has two faces. As spread, it expands an array or object to copy or merge it: widely used to apply default settings and then override them. As rest, it gathers "everything that's left" into an array, for example to accept a variable number of arguments.
const baseConfig = { theme: "dark", lang: "fr" };
const overrides = { lang: "en" };
const config = { ...baseConfig, ...overrides };
// { theme: "dark", lang: "en" }
const scores = [12, 18, 9];
const allScores = [...scores, 20]; // [12, 18, 9, 20]
function sumAll(...numbers) {
return numbers.reduce((sum, n) => sum + n, 0);
}
console.log(sumAll(1, 2, 3)); // 6Mental exercise before moving on to the quiz: in { ...baseConfig, ...overrides }, what happens if both objects define lang? The last one written wins. This ordering detail is exactly what makes the "defaults then overrides" pattern possible.
const { city } = user; do?function log(...args), what is args inside the function?const copy = { ...original };, are nested objects duplicated?