IntermediateLesson 8 of 16
Destructuring, Spread & Rest – JavaScript
Unpacking, copying and merging values.
Destructuring breaks objects and arrays into individual variables – with renaming and default values:
const person = { name: "Ada", alter: 36, stadt: "London" };
const { name, alter, land = "UK" } = person;
console.log(name, alter, land);
const { stadt: wohnort } = person; // rename
console.log(wohnort);
const [erste, zweite, ...rest] = [10, 20, 30, 40];
console.log(erste, zweite, rest); // 10 20 [30, 40]
let x = 1, y = 2;
[x, y] = [y, x]; // swap values
console.log(x, y); // 2 1Also useful in function parameters – especially for objects with many options:
function zeige({ name, alter = 0 }) {
return name + " (" + alter + ")";
}
console.log(zeige({ name: "Ada", alter: 36 }));
console.log(zeige({ name: "Bob" }));
for (const [k, v] of Object.entries({ a: 1, b: 2 })) {
console.log(k, v);
}The spread operator ... unpacks arrays and objects – ideal for copying and merging without modifying the original:
const a = [1, 2], b = [3];
console.log([...a, ...b, 4]); // [1, 2, 3, 4]
const standard = { laut: false, farbe: "blau" };
const optionen = { ...standard, farbe: "rot" }; // later values win
console.log(optionen);
console.log(Math.max(...a, ...b)); // 3WarningSpread and
Object.assign copy only shallowly: nested objects are shared. For a true deep copy, use structuredClone(object).const original = { a: { b: 1 } };
const flach = { ...original };
const tief = structuredClone(original);
original.a.b = 2;
console.log(flach.a.b, tief.a.b); // 2 1