Rest and Spread

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Rest and Spread

Rest and Spread operators in ES6 can help you write concise code. They’re kind of confusing if you haven’t seen them before, because they take up the same form—....

In this lesson, you’ll learn what spread and rest operators are, and why they’re useful.

Array spread

The array spread operator spreads out an array into a comma-delimited list. To help you remember array spread, envision spreading a block of butter on a piece of bread.

const array = [1, 2, 3]

// These two are the same
console.log(...array) // 1 2 3
console.log(1, 2, 3) // 1 2 3

You can spread arrays anywhere, like when calling a function, or into other arrays.

const names = ['Zell', 'Thomas', 'Jacin']
const logNames = (first, second, third) => {
  console.log(first) // Zell
  console.log(second) // Thomas
  console.log(third) // Jacin
}

// Spreading arrays as arguments
logNames(...names)
// Spreading arrays into arrays
const names = ['Zell', 'Thomas', 'Jacin']
const array = [...names]

console.log(array) // 'Zell', 'Thomas', 'Jacin'

Spread is a great substitute for Array.concat

Since you can spread arrays into other arrays, spread becomes a great substitute for concat.

Here’s how you can prepend a number to an array:

const itemToAdd = 1
const existingArray = [2, 3]

// Without spread
const combinedArray = [itemToAdd].concat(existingArray)

// With spread
const combinedArray = [itemToAdd, ...existingArray]

Here’s how you can append items to an array

const array = [2, 3]

// adding 4 and 5 without spread
const combinedArray = array.concat(4, 5)

// adding 4 and 5 with spread
const combinedArray = [...array, 4, 5]

To combine two arrays, you spread both arrays in a new array.

const firstArray = [0, 1]
const secondArray = [2, 3]

const combinedArray = [...firstArray, ...secondArray] // [0, 1, 2, 3]

You can even spread array items in the middle of another array.

const array = [2, 3]
const combinedArray = [1, ...array, 4, 5] // [1, 2, 3, 4, 5]

Spreading instead of Array.from

The spread operator works on array-like objects too. You can use it to convert HTMLCollections and NodeLists into arrays if you dislike Array.from.

const items = document.querySelectorAll('.item')

// These two give the same results
const array = Array.from(items)
const array2 = [...items]

You can choose whichever you prefer. Both do the same thing, and both have the same browser support.

Array Rest

The array rest operator packs comma-delimited arguments into an array. It’s the opposite of spread.

Let’s say you want to create a function that takes in ten arguments. Here’s how you’d use it:

logNames('Zell', 'Thomas', 'Jacin', 'Vincy', 'Jing', 'Soares', 'Gabrielle', 'Justin')

You can pack all arguments into an array by using a rest operator.

const logNames = (...names) => {
  names.forEach(name => console.log(name))
}

logNames('Zell', 'Thomas', 'Jacin', 'Vincy', 'Jing', 'Soares', 'Gabrielle', 'Justin')

Array Rest and Destructuring

When you destructure an array you can pack the “rest of the array” into a variable with the rest operator.

const scores = [100, 99, 98]
const [first, ...restOfScores] = scores

console.log(first) // 100
console.log(restOfScores) // [99, 98]

Object Spread

You can use the spread operator to spread an object’s properties into another object.

const fruitBlender = {
  blendKiwi: true,
  blendMango: true
}

const megaBlender = {
  blendGuava: true,
  ...fruitBlender
}

console.log(megaBlender)
// {
//   blendGuava: true,
//   blendKiwi: true,
//   blendMango: true,
// }

Object Rest

When you destructure objects, you can pack remaining properties into a variable with the rest operator.

const fruitBlender = {
  blendKiwi: true,
  blendMango: true,
  blendOrange: true,
  blendPapaya: true
}
const { blendKiwi, ...otherProps} = fruitBlender

console.log(otherProps)
// {
//   blendMango: true,
//   blendOrange: true,
//   blendPapaya: true
// }

A note about object rest and spread

Object spread and object rest operators are finalized in ES8. Edge doesn’t support object spread and object rest yet (as of March 2018).

Exercise

Practice using spread and rest operators by doing the following:

  1. Spread an array in a console.log
  2. Spread an array when calling a function
  3. Concatenate arrays with spread
  4. Use the rest operator as a function argument
  5. Destructure an array; pack items into a variable with rest
  6. Destructure an object; pack remaining properties with rest
  7. Spread an object into another object

Answers

  • Spread an array in a console.log
const array = ['one', 'two', 'three']
console.log(...array)
  • Spread an array when calling a function
addThemUp(...array)
  • Concatenate arrays with spread
const one = [1, 2, 3]
const two = [4, 5, 6]
const combined = [...one, ...two]
console.log(combined) // [1, 2, 3, 4, 5, 6]
  • Use the rest operator as a function argument
const addThemup = (...args) => {
  console.log(...args)
}
  • Destructure an array; pack items into a variable with rest
const array = ['one', 'two', 'three']
const [one, ...rest] = array
console.log(one) // one
console.log(rest) // [two, three]
  • Destructure an object; pack remaining properties with rest
const zell = {
  firstName: 'Zell',
  lastName: 'Liew',
  gender: 'male'
}
const {firstName, ...rest} = zell
console.log(firstName) // Zell
console.log(rest) // {lastName: "Liew", gender: "male"}
  • Spread an object into another object
const person = {
  firstName: 'Zell',
  lastName: 'Liew',
}

const male = {
  gender: 'male'
}

const zell = {...person, ...male}