ISAAC
ISAAC

Reputation: 159

What is the difference between: t = a and t = [...a] when a is an array?

I am trying to understand if there is any difference between these two methods for copying an array?

 let a = [1,2,3,4];
 t = a; // -> t = [1,2,3,4]
 t = [...a] // -> t = [1,2,3,4]

Upvotes: 1

Views: 64

Answers (3)

Meet Zaveri
Meet Zaveri

Reputation: 3059

Main difference is that when you use ... spread operator, you actually share a shallow copy of a array. That means a becomes immutable and a new array is passed with new reference pointer in memory to t.

When you simply copy, i.e. t=a, you share a reference pointer in memory. So whenever you change contents of t, it automatically updates a also.

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

let t = a; // assigning reference to t

The first method is just assigning the reference of a to t, which means if you change the value at either a or t, it will affect both a and t as they are pointing to the same memory location

let a = [1,2,3,4];
let t = a;

a[0] = 120

console.log(a)
console.log(t)

let t = [...a];         // creating a shallow copy of a and assign it to t

Where's second method makes a shallow copy and assign it to

let a = [1,2,3,4];
let t = [...a];

a[0] = 120

console.log(a)
console.log(t)

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370799

The first, t = a, means that the array that t references is the same array as a. If a is changed, t will be changed as well:

let a = [1, 2, 3, 4];
t = a;
a.push(10);
console.log(t);

The second, t = [...a], means that t is now a new array which contains every item that was in the original array. Subsequent changes to the old array will not affect t:

let a = [1, 2, 3, 4];
t = [...a];
a.push(10);
console.log(t);

Note that this is only in respect to mutations of the original a array. If the items that a initially contains are objects, then those objects will not be deep-copied when t is created - there will still be only one object in memory for each item in the original array. So, mutations to any of those objects in the original array will be seen as affecting t, even if t is a new array:

const a = [{ prop: 'val', prop2: 'val2' }];
const t = [...a];
a[0].anotherProp = 'anotherVal';
console.log(t);

Upvotes: 6

Related Questions