timmyLtus
timmyLtus

Reputation: 274

What is the need to copy, or slice, an array vs. creating a variable that is just equal to existing one?

let a = {"foo": 99};
let b = a;
// console.log(b)  {"foo": 99}

a.foo = 33;
// console.log(b)  {"foo": 33}

I understand in the scenario above that if I use objects, the variable referencing the original object will reflect the value of the original object.

But if I do this with arrays:

let a = [1,2,3];
let b = a;

a = [99,99,99];
// console.log(b) [1,2,3];

variable b still references the original value of a even after a changed so then what would the person of creating a copy via slice() serve?

Upvotes: 4

Views: 387

Answers (2)

Anand
Anand

Reputation: 408

JavaScript is a loosely typed language, which means that you don’t have to specify what type of data will be stored in a variable in advance.

In your case, you have selected let a=[1,2,3]; which gets overridden later. but let suppose you had something like the below.

let a = [{name: 'David'}, {name: 'Tim'}];
let b = a;
b[0].name = 'Bruce';
console.log(a[0].name); //Bruce

In the aforementioned example, you see that the array assignment to a different variable won't help you retain the actual value in your original array. Hence, it's always better to copy the array instead of just assigning it to another variable if it needs modification.

In addition, when copying it is always better to do a deep copy to avoid missing information.

Upvotes: 1

shreyasm-dev
shreyasm-dev

Reputation: 2834

This is because, by doing a = [99, 99, 99], you are creating an entirely new object, and "resetting" a. But when doing a.foo = 33, you are modifying an existing object and references to it.

You can see that when I set a[0] instead of a, b still equals a:

let a = [1, 2, 3];
let b = a;

a[0] = [99, 99, 99];
console.log(b);

When using the slice() method, b retains a's original value.

Example:

let a = [1, 2, 3];
let b = a;

a = a.slice(2);
console.log(a, b);

Upvotes: 2

Related Questions