Lesson 7 of 8

Spread and rest

Goal

Two uses for three dots

01

Explanation

The three dots ... have two opposite uses. The first is spread, which unpacks the contents of an array or an object right where you write it: [...list, item] makes a new array with one extra item, and { ...defaults, ...options } makes a new object that combines the two. In both cases the original stays as it was.

The second is the rest parameter, which gathers whatever is left into an array. A function declared as function append(list, ...items) accepts any number of values after the first one, and they all arrive inside the array items. A rest parameter can only come last in the parameter list.

When you merge two objects and a key appears in both, the last value wins, so put the defaults first and then whatever the caller passes in. And keep in mind that this copy is shallow: an object nested inside another one isn't copied but shared between the copy and the original, so if you change it in the copy, it changes in the original too.

02

Your task

Write settings(overrides) so it returns a new object that merges defaults with overrides without changing defaults, and write append(list, ...items) so it returns a new array with the items of list followed by every value passed after it.

Checks

6 checks
  1. Merging keeps the defaults and lets new values override them
  2. Merging returns a new object and leaves defaults unchanged
  3. append accepts any number of items
  4. append doesn't change the original array
  5. append takes the items with a rest parameter
  6. The page shows four tasks and the original array still has two
03

Hints

0/3
index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.