JavaScriptLesson 11 of 16

Destructuring and spread

Destructuring pulls values out of an array or object into separate variables in one line. The three dots do the opposite: they spread an array or object out so you can copy it or merge it with another.

Key points

  • const [first, second] = list makes variables in the order of the items
  • const { name, age } = user makes variables by key name; = "…" sets a default
  • { ...a, ...b } is a new object: a copy of a with the keys of b laid on top
  • [...list, "new"] is a copy of the array with one more item
  • function sum(...numbers): a rest parameter gathers all arguments into an array

Example

const [gold, silver, ...rest] = ["Ana", "Ben", "Cleo", "Dan"];console.log(gold, silver, rest); const user = { name: "Kai", age: 27 };const { name, age, country = "unknown" } = user;console.log(name, age, country); const older = { ...user, age: 28 };console.log(older, [...rest, "Eve"]);console.log(Math.max(...[3, 9, 4]));

rest took everyone who did not fit into gold and silver. The object had no country key, so the default was used. Spread made a new object, and the original user still has age 27.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Merge defaults and userSettings into a new settings object with spread (defaults itself must stay unchanged), take theme and fontSize out with destructuring, and rewrite sum with a rest parameter so it adds up any number of values. Output: Theme: dark, size: 16, Sound: true, Defaults untouched: light and 10.

Output

What your program prints appears here.