DEV Community

Fabio Russo
Fabio Russo

Posted on

Array reference... and how to not!

Sometimes it's sticky...

Look at this code... what do you think is going to happen to the breeds array?

let breeds = ["Labrador","Akita","Siamese"]

// Let's make an array of only Dogs Breed... splice out Siamese.

let doggy = breeds;

doggy.splice(2)

console.log(doggy)
// -> ["Labrador", "Akita"]

console.log(breeds)
// -> ["Labrador", "Akita"]
Enter fullscreen mode Exit fullscreen mode

So... we just wanted to change the doggy array, and not the breeds one.

We told JavaScipt:

  1. I want a new array;
  2. Call It doggy;
  3. Give doggy the same values of Breeds;
let doggy = breeds;
Enter fullscreen mode Exit fullscreen mode

But Javascript with the "=" has created a REFERENCE.

With our declaration doggy and breeds are pointing at the "same object" by reference... the same memory, and by changing one, you're changing both!

evil TWINS

twins

Let's make a list... how not to create a reference

If we want to pass just the values of an array into another, and at the same time create a "new object".
We can use this useful methods.

//1. Create a copy with slice.
let doggy = breeds.slice();

//2. Create a concatenation with an empty array.
let doggy = [].concat(breeds);

//3. Spread an array into another one.
let doggy = [...breeds];

//4. Use the Array.from() method, to create an array, with the same value of //another one
let doggy = Array.from(breeds);
Enter fullscreen mode Exit fullscreen mode

All the methods, up here, are creating a totally NEW doggy array, without any reference to the breeds one.
You can now take off the Siamese without any collateral effect.

let breeds = ["Labrador","Akita","Siamese"]

let doggy = breeds.slice();

doggy.splice(2)

console.log(doggy)
// -> ["Labrador", "Akita"]

console.log(breeds)
// -> ["Labrador", "Akita", "Siamese"]
Enter fullscreen mode Exit fullscreen mode
Now they're in different arrays... but can still love each other!

love

Top comments (0)