2

I'm struggling to fully understand how the spread/rest operator works in JS. I have read the MDN docs but it's still not fully clear to me.

I've included an example below where I've used it and it has worked as desired.

const users = [
  {
    name: 'Samir',
    age: 27,
    favoriteBooks:[
      {title: 'The Iliad'},
      {title: 'The Brothers Karamazov'}
    ]
  },
  {
    name: 'Angela',
    age: 33,
    favoriteBooks:[
      {title: 'Tenth of December'},
      {title: 'Cloud Atlas'},
      {title: 'One Hundred Years of Solitude'}
    ]
  },
  {
    name: 'Beatrice',
    age: 42,
    favoriteBooks:[
      {title: 'Candide'}
    ]
  }
];

const books = users
  .map(user => user.favoriteBooks.map(book => book.title))
  .reduce((arr, titles) => [...arr, ...titles], []);
btow54
  • 111
  • 2
  • 8
  • `[...arr, ...titles]` is equivalent to `[arr[0],arr[1],/*etc*/,titles[0],titles[1],/*etc*/]`, `...` just spreads the individual elements out into the structure – Patrick Evans Jan 17 '20 at 18:13
  • https://stackoverflow.com/questions/34559918/spread-syntax-es6/57680090 – Taki Jan 17 '20 at 18:15

1 Answers1

4

There are many resources on this topic other than MDN if you search around.

How does the spread and rest operators in JS work?

JavaScript ES6: Spread Operator and Rest Parameters

Javascript's three dots ( ... ): Spread vs rest operators

Rest parameters and spread syntax


Spread

The spread operator “spreads” the values in an iterable (arrays, strings)

Essentially, spread will iterate over each item of an array in this case. Outputting array[0] array[1] array[2] etc.

var a = [1,2,3];
var b = [4,5,6];

console.log([...a, ...b]); // [1,2,3,4,5,6]

or

var a = ['x', 'y', 'z'];
test(...a);

function test(param1, param2, param3) {
    // param1 = 'x'
    // param2 = 'y'
    // param3 = 'z'
}

Rest

The rest parameter allows us to pass an indefinite number of parameters to a function and access them in an array.

Rest works in a similar way as the spread operator but will iterate over all arguments passed to a function and allow you to access them in array.

test(1,2,3,4,5,6)

function test(...args) {
    console.log(args); // [1,2,3,4,5,6]
    // Instead of ar
}
ButchMonkey
  • 1,873
  • 18
  • 30