2

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] : '';
Coder
  • 540
  • 1
  • 11
  • 34

3 Answers3

4

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.

Eddie D
  • 1,120
  • 7
  • 16
1

The difference if you use:

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

Here it will assign reference of numbers to mainArray

instead of this:

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

Here it will create new array from numbers's elements and will assign it to mainArray

Vivek
  • 1,465
  • 14
  • 29
1

The spread operator (...) spreads out an array into individual values instead of an array of values. As is shown in the below code snippet numbers is an array of integers while ...numbers is 3 separate integers. So [...numbers] will give you a new array with the same values and numbers is just a reference to the existing array.

var numbers = [1, 2, 3]
console.log(numbers);
console.log(...numbers);
Salman A
  • 262,204
  • 82
  • 430
  • 521
Cory Kleiser
  • 1,969
  • 2
  • 13
  • 26