DEV Community

Fabio Russo
Fabio Russo

Posted on

15 5

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay