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] : '';
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] : '';
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]
andy = x
then we sayx.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.
The spread operator (
...
) spreads out an array into individual values instead of an array of values. As is shown in the below code snippetnumbers
is an array of integers while...numbers
is 3 separate integers. So[...numbers]
will give you a new array with the same values andnumbers
is just a reference to the existing array.The difference if you use:
Here it will assign reference of
numbers
tomainArray
instead of this:
Here it will create new array from
numbers
's elements and will assign it tomainArray