Search code examples
javascriptecmascript-6ecmascript-5

What is the difference when we use array names instead of spread operator?


What is the difference if I use:

var numbers = [1, 2, 3]
var mainArray = (numbers.length > 1) ? numbers : '';

instead of this:

var numbers = [1, 2, 3]
var mainArray = (numbers.length > 1) ? [...numbers] : '';

Solution

  • Since assigment of data structures points to the same space in memory, if you have two variables referencing the same array, altering one variable will alter the other. That is to say:

    if x = [1, 2, 3] and y = x then we say x.push(5) y will also have that 5 because they are pointing to the same instance. If you use [...x] you are creating a copy of x. It consumes O(n) memory, a new reference. So if x is altered, y will be uneffected.

    spreads are clean and neat but they do have overhead. They will effect performance if used on a very large data set.