Jump to content

Recommended Posts

Sorry for stupid question. I can't understand the purpose of cloning an array in JS. Why do we need it?

What is the difference between:

let a = [];
let b = a;

and:

let a = [];
let b = a.slice(0);

 

Share this post


Link to post
Share on other sites

In the first example, if you change a, b will also change because they're both pointing to the same thing. In the second example, both a and b can be changed independently of each other because they're two different arrays that merely have identical content.

  • Thanks 1

Share this post


Link to post
Share on other sites

Ingolme:  I do not understand your reply.

In the second example.  If I change a, so too will b change, because the value of a.slice(0) is determined by the value of a.

in the first example. can I not assign a new value to b without affecting the value of a?

Roddy

Share this post


Link to post
Share on other sites

The slice() method creates a copy of the array, it does not create a reference to the array. After the copy has been made, it can be changed without modifying the original array.
 

/* Two variables pointing to the exact same array */
var a = ["a", "b", "c"];
var b = a;

b[0] = "d";

console.log(a[0]); // Prints "d"

/* A variable containing a copy of the array in another variable */
var a = ["a", "b", "c"];
var b = a.slice(0);

b[0] = "d";

console.log(a[0]); // Prints "a"

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×