Spread & Rest

Spread

The spread operator allows us to expand the elements of an array or the properties of an object into another array or object, respectively.

const countries = ["au", "nz", "sg", "jp", "us"];
// console.log(countries[0], countries[1], countries[2], countries[3], countries[4])
console.log(...countries)

// can be used to create a shallow copy of the original array
const countriesCopy = [...countries]

const scores = [29, 24, 28, 92, 1]
const moreScores = [2, ...scores, 32, 88]
console.log(moreScores)
const john = { name: "john", location: "iceland", year: 2003 }

// This operator can be used for creating a shallow copy of the original object.
// const cloneOfJohn = Object.assign({}, john)
const cloneOfJohn = { ...john }

// Combine two objects
const programmer = { experience: 5, language: "snake python" }
const johnTheProgrammer = { ...john, ...programmer }

Rest

In function definitions, the rest operator allows us to accept an unknown number of arguments, which are stored in an array.

const printMyFavoriteColours = (...colours) => {
  console.log(`My favorite colours are:`)
  for (let colour of colours) {
    console.log(colour)
  }
}
printMyFavoriteColours("red", "blue")
printMyFavoriteColours("white", "grey", "yellow")

In destructuring, it allows us to represent the remaining elements of an array as a new array.

const numbers = [1, 2, 3, 4, 5]
const [n1, n2, ...others] = numbers
console.log(n1, n2, others)

Last updated