Simple but often overlooked tech nuggets

Simple but often overlooked tech nuggets

ES6 ... operator confusion: Rest vs Spread

Duc Trinh's photo
Duc Trinh
·Jun 7, 2022·

1 min read

Play this article

Sometimes, you see the following piece of code:

const arr = [1,2,3, 4]
console.log(...arr) // 1 2 3 4
console.log([...arr, 5]) // [1, 2, 3, 4, 5]

It totally makes sense, right? But how about the following?

const foo = (...args) => {
  return args
}
console.log(foo([1,2,3,4])) // [[1,2,3,4]] -> notice the deeply nested array

What is that? Why does args not return 1 2 3 4 like the first example? The answer is: despite the similar looking operator (...), the first example use Spread operator, while the second one uses Rest operator

This is how to use Spread operator for the case above:

const foo = (args) => {
  return [...args]
}
console.log(foo([1,2,3,4])) // [1,2,3,4] -> no more deeply nested array

In short:

  • Use Spread syntax to turn iterable objects into individual elements (ex: [1,2,3] -> 1,2,3)
  • Use Rest syntax to group individual elements into iterable objects (ex: 1,2,3 -> [1,2,3])

Ref: developer.mozilla.org/en-US/docs/Web/JavaSc..