0

Using this object for an example

 ingredients = {
     salad: 3,
     bacon: 1,
     cheese: 1,
     meat: 0
 }

And I have 2 expressions which have different result one without spread operator

Object.keys(ingredients).map(igKey=>{ 
    return [Array(3)]
})

and another with spread operator

Object.keys(ingredients).map(igKey=>{ 
    return [...Array(3)]
})

Result without spread operator

(4) [Array(1), Array(1), Array(1), Array(1)]
0: [Array(3)]
1: [Array(3)]
2: [Array(3)]
3: [Array(3)]

Result with spread operator

(4) [Array(3), Array(3), Array(3), Array(3)]
0: (3) [undefined, undefined, undefined]
1: (3) [undefined, undefined, undefined]
2: (3) [undefined, undefined, undefined]
3: (3) [undefined, undefined, undefined]

I read spread operator is used to combine multiple arrays, what operation does spread operator does in this example?

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
Roshan
  • 873
  • 12
  • 33
  • If you change `[Array(3)]` in your first example to `Array(3)` (no `[ ]`), they'll give the same results. That would in fact be the preferred way to do things, as `[... Array(3)]` creates an array, then creates *another* array and copies the first to the second. Simply `Array(3)` by itself will suffice. – Pointy Nov 30 '19 at 12:31
  • I would recommend using `Array.from({length: 3})` – Bergi Nov 30 '19 at 12:42

0 Answers0