Destructuring, spread and week 4 review
Destructuring and the spread operator are two ES6 tools that make code shorter and clearer. The first one is used to extract values from an array or an object and store them in variables in a single line. The second one is used to expand the elements of an array somewhere else, copying or combining lists without modifying the originals. You will see them in almost any modern code.
Destructuring arrays
With brackets on the left of the equals sign you assign each element to a variable according to its position. You can skip positions by leaving a gap with a comma, give default values with = and collect the remaining elements with three dots. A popular trick is swapping two variables without a temporary variable.
const podium = ['gold', 'silver', 'bronze', 'fourth', 'fifth'];
const [first, second] = podium;
console.log(first, second); // gold silver
const [, , third, ...others] = podium;
console.log(third, others); // bronze [ 'fourth', 'fifth' ]
const [a, b = 'default'] = ['only one'];
console.log(a, b); // only one default
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1Destructuring objects
With braces you extract properties by name, not by position, so order does not matter. You can rename with a colon, set default values and destructure directly in a function's parameters. You will use this when you work with objects in week 6 and with server responses in week 8.
const user = { name: 'Nora', age: 31, city: 'Quito' };
const { name, age } = user;
console.log(name, age); // Nora 31
const { city: town, country = 'Ecuador' } = user;
console.log(town, country); // Quito Ecuador
function greet({ name, age }) {
return `${name} is ${age}`;
}
console.log(greet(user)); // Nora is 31The spread operator
Three dots in front of an array expand it into its elements. It is used to copy an array, join several and add elements without mutating the original, exactly what modern applications need. It also works with objects, where it copies the properties; if a key repeats, the last one wins. Important: the copy is shallow, meaning nested objects are still shared between the copy and the original. For deep copies there is structuredClone.
const base = [1, 2, 3];
const copy = [...base];
const bigger = [0, ...base, 4];
const joined = [...base, ...[10, 20]];
console.log(copy, bigger, joined);
// [ 1, 2, 3 ] [ 0, 1, 2, 3, 4 ] [ 1, 2, 3, 10, 20 ]
console.log(Math.max(...base)); // 3
const settings = { theme: 'light', size: 12 };
const updated = { ...settings, theme: 'dark' };
console.log(updated); // { theme: 'dark', size: 12 }
console.log(settings); // { theme: 'light', size: 12 }
const nested = { list: [1] };
const shallow = { ...nested };
shallow.list.push(2);
console.log(nested.list); // [ 1, 2 ] shared!Destructuring in real life
These two techniques appear constantly in real projects. Destructuring lets a function return several values in an array or an object and lets the caller receive them directly in named variables. Spread makes it easy to update state without mutating it, which is essential in libraries such as React. It is also used to combine settings: the default options go first and the ones chosen by the user after, so the latter win. Remember that both are syntactic sugar: they do nothing you could not do with more lines, but they make the code shorter and more readable.
function minMax(list) {
return { min: Math.min(...list), max: Math.max(...list) };
}
const { min, max } = minMax([4, 9, 2, 7]);
console.log(min, max); // 2 9
const defaults = { color: 'blue', size: 10, rounded: false };
const userChoice = { size: 14 };
console.log({ ...defaults, ...userChoice });
// { color: 'blue', size: 14, rounded: false }Practice both techniques with your own lists and objects until they feel natural. A good exercise is to rewrite old code that used indexes and concat with destructuring and spread, and check that the result is identical.
理解度チェック
問題 1 / 7Which method returns a new array with each element transformed?
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字