CodeBlanks Logo Icon CodeBlanks

Summary - Spread and rest

JavaScript course · Advanced · Lesson 35/100

Build a function that merges a config object with defaults using spread and rest.

Summary - Spread and rest

In this group you learned five essentials of spread and rest: array spread, object spread, the rest parameter, shallow copy and spread in calls. The same three dots are one symbol; depending on context it either expands (spread) or collects (rest).

There are two tasks: first you will write a flexible config merger with the rest parameter; then you will combine rest and spread in a call inside one function. Remember the override rule and the shallow-copy caveat.

Exercise Flexible config merger

Write a function called buildConfig(...parts). The rest parameter parts collects any number of config objects as an array. Inside the function body, create an empty object called result. Loop over parts with for...of and merge each part into result using { ...result, ...part }. Finally return result and call the function with at least two objects inside console.log.

Show example solution
function buildConfig(...parts) {
  let result = {};
  for (const part of parts) {
    result = { ...result, ...part };
  }
  return result;
}
console.log(buildConfig({ a: 1 }, { b: 2 }, { a: 9 }));

Exercise Rest and spread in a call together

Write a function called logMax(...nums). The rest parameter nums collects every number as an array. In the body, find the largest value with Math.max(...nums) and log it with console.log. Then call the function with at least four numbers.

Show example solution
function logMax(...nums) {
  console.log(Math.max(...nums));
}
logMax(3, 7, 2, 9, 1);

Test yourself

  1. Match all the concepts

    ...arr (array literal)
    Merge arrays
    {...obj}
    Merge objects
    ...args (parameter)
    Collect remaining arguments
    fn(...arr)
    Expand array into arguments
  2. Rest and spread in a call

    function sum(...numbers) {
      let total = 0;
      for (const n of numbers) total += n;
      return total;
    }
    const args = [1, 2, 3];
    console.log(sum(____));
    Show answer
    function sum(...numbers) {
      let total = 0;
      for (const n of numbers) total += n;
      return total;
    }
    const args = [1, 2, 3];
    console.log(sum(...args));

All lessons in Advanced