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"]
So... we just wanted to change the doggy array, and not the breeds one.
We told JavaScipt:
- I want a new array;
- Call It doggy;
- Give doggy the same values of Breeds;
let doggy = breeds;
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!
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);
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"]
Top comments (0)