Skip to content

Latest commit

 

History

History

13 - Rest and Spread Operator

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Section 13: Rest and Spread Operators

The Rest Operators ...

The rest operator ... is used to gathering together variables. It can be used in function arguments whenever we want to capture a list of variables or a list of arguments.

function addNumbers(...numbers) {
  return numbers.reduce((sum, number) => sum + number, 0);
}

addNumbers([1, 2, 3, 4, 5]);


The Spread Operators

The spread operator ... is used to flattening or spreading gathering variables.

const defaultColors = ['red', 'green'];
const userFavoriteColors = ['orange', 'yellow'];

// use concat() method
// ['red', 'green', 'orange', 'yellow']
colors = defaultColors.concat(userFavoriteColors);

// use spread operators
colors = [...defaultColors, ...userFavoriteColors];

We can also mix and match the spread and rest operators.

function validShoppingList(...items) {
  if (item.indexOf('milk') < 0) {
    return ['milk', ...items];
  }
  return items;
}

validShoppingList('oranges', 'bread', 'eggs');

Imaging that we're going to update the legacy API in a JavaScript library. We can also use rest and spread operators to catch the balance.

const MathLibrary = {
  calculateProduct(...rest) {
    console.log('Please use the multiply method instead');
    return .this.multiply(...rest);
  },
  multiply(a, b) {
    return a * b;
  }
}


[Exercise] Many, Many Arguments

Question

Refactor the following function to use the rest operator. Remember, an argument using the rest operator does not need to be called 'rest'.

function product(a, b, c, d, e) {
  var numbers = [a, b, c, d, e];

  return numbers.reduce(function(acc, number) {
    return acc * number;
  }, 1)
}

Solution

function product(...numbers) {
  return numbers.reduce(function(acc, number) {
    return acc * number;
  }, 1)
}


[Exercise] Spreadin' Arrays

Question

Refactor the following to use the spread operator.

function join(array1, array2) {
  return array1.concat(array2);
}

Solution

function join(array1, array2) {
  return [...array1, ...array2];
}


[Exercise] Mixing Rest and Spread

Question

Refactor the following to use only the rest operator.

function unshift(array, a, b, c, d, e) {
  return [a, b, c, d, e].concat(array);
}

Solution

function unshift(array, ...rest) {
  return [...rest, ...array];
}