2

I wanted to concat two arrays in JavaScript so I wanted to know if the ES6 spread operator ... is costlier than array.concat?

Does that mean we should use the ... syntax wisely and only when utmost needed?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Karan Sah
  • 152
  • 7
  • 2
    Does this answer your question? [spread operator vs array.concat()](https://stackoverflow.com/questions/48865710/spread-operator-vs-array-concat) – Nicolae Maties Feb 11 '20 at 15:40
  • 2
    Mandatory link to [Eric Lippert on performance](https://ericlippert.com/2012/12/17/performance-rant/). – VLAZ Feb 11 '20 at 15:40
  • 1
    Does this answer your question? [Spread Syntax ES6](https://stackoverflow.com/questions/34559918/spread-syntax-es6) – Taki Feb 11 '20 at 15:52

1 Answers1

2
let arrayVar = [1, 2, 3];
let array2 = [...arrayVar, 4];

is equivalent to

var arrayVar = [1, 2, 3];
var array2 = [].concat(arrayVar, [4]);

per https://babeljs.io/

Jawi
  • 360
  • 1
  • 8
  • Your second example could also be written as`var array2 = arrayVar.concat([4]);`. – Ed Lucas Feb 11 '20 at 15:49
  • @EdLucas true, I just transcribed the output that babeljs.io provided for the given input. – Jawi Feb 11 '20 at 15:50
  • 1
    @EdLucas in all honesty, it's probably even more accurate as `[].concat(arrayVar, 4)`. Although you get the same result in the end, so it hardly matters. I wouldn't be surprised if the exact same steps are taken in either case. – VLAZ Feb 11 '20 at 15:53