0

I am having a little trouble differentiating between spread and rest. Could someone explain to me if either spread or rest is being used within the reduce functions return statement?

This is what I am not understanding:

return [currentValue, ...accumulator]

inside of

let str = 'KING';

const reverseStr = str => {
  return str
    .split('')
    .reduce((accumulator, currentValue) => {
      return [currentValue, ...accumulator];
    }, [])
    .join('');
};

1 Answers1

1

Rest syntax always creates (or assigns to) a variable, eg:

const [itemOne, ...rest] = arr;
//     ^^ created  ^^^^

Spread syntax only results in another array (or object) expression - it doesn't put anything into variables. Here, you're using spread syntax to create a new array composed of currentValue and the values of accumulator.

return [currentValue, ...accumulator];

is like

return [currentValue, accumulator[0], accumulator[1], accumulator[2] /* ... */];

You're spreading the items of accumulator into the array that's being returned.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320