Help understanding the difference between spread and rest operators

Okay so i’m thoroughly confused. In the ES6 section of JavaScript we learn about the spread operator. Which I assume is the “…” with a following name value.

Am I right in assuming spread is primarily used for placing an array in a functions parameters when the function expects something different from an array?.

and is rest primarily used in destructuring assignment to encompass the remaining indexes of an array
e.g const [a,b, …rest] = [0, 1 , 2 , 3 , 4 , 5 , 6]?
I’m mainly confused as they share the same syntax of “…” ? am I close or way off ? thanks in advance.

Hi @mikelewell

You’re pretty much there, I like to think of it like this.

Rest: quite literally the rest of the data. It will always collect the data in an array, so:

function test(arg1, arg2, ...restOfArgs) {  }

const arrow = (arg1, arg2 ...restOfArgs) => {  }

const [el1, el2, ...restOfElements] = [0, 1, 2, 3, 4, 5]

Spread: again, literally spread the data over the input. Will be an iterable in some form (array, object, string etc…) so:

const arrayOfData = [1, 2, 3, 4]
function test(a, b, c, d) {
  // a = 1
  // b = 2
  // c = 3
  // d = 4
}
test(...arrayOfData)

const stringSpread = [...'hello']
// ['h', 'e', 'l', 'l', 'o']

const arraySpread = [
  ...[1, 2, 3],
  ...[4, 5, 6]
]
// [1, 2, 3, 4, 5, 6]

const toSpread = { key: 'value' }
const objectSpread = {
   ...toSpread,
  secondKey: 'secondValue'
}
// { key: 'value', secondKey: 'secondValue' }
// Note: objectSpread behaves like Object.assign, so any key that already exists will be overwritten.

Does that make sense?

2 Likes

Hi thanks for getting back. Yes that’s much clearer thank you!