1

I thought that when using the slice() method, we were just making a shallow copy, meaning that if I modify any value of the copy that is referenced, it will be reflected on the original too.

Example:

const arr = [
  { name: "John", lastName: "Doe" },
  { name: "Chris", lastName: "Dior" },
];

const arrCopy = arr.slice(); // Creating shallow copy

arrCopy[0].name = "Stella"; // Changed in copy AND original as it should
arrCopy.pop(); // Deleting last element of the copy, ONLY disappears in the copy

console.log(arr); // has both elements
console.log(arrCopy); // has only one

Why does the second object is gone just in the shallow copy? I thought the arr and arrCopy were pointing to the same object. (an array with objects)

Thanks in advance, Im really new to programming in general and this topic is getting confusing sometimes.

2
  • The values in arr are references to objects, that's what gets copied to arrCopy. When you do arrCopy.pop() you remove the last value (i.e. reference to an object) from arrCopy. Also, when you do arrCopy[0].name = "Stella" you are changing the object referenced by both arrays, you aren't actually changing the array per se. :-) Commented Mar 22, 2021 at 3:43
  • You said "if I modify any value of the copy that is referenced, it will be reflected on the original", but this is NOT what a shallow copy means. A shallow copy is a completely new, unrelated array that is a COPY of the original (so it has the same contents.) The "shallow" part is that if the contents contain any reference values (Objects, Arrays, Functions, etc -- as opposed to primitives like numbers and strings), then when one of those referenced items changes (by any means), both references will still point to the (now changed) item so the changes will be visible via the references. Commented Mar 22, 2021 at 4:33

1 Answer 1

4

It's just as you're saying here:

const arrCopy = arr.slice(); // Creating shallow copy

The new array is separate from the old array. Changing the new array structure without changing any of its containing objects will result in only the new array changing, not the old array changing.

I thought the arr and arrCopy were pointing to the same object. (an array with objects)

No. Both arr and arrCopy are separate containers. Those containers contain pointers to the same objects, but the containers themselves are different - so, changing one of the containers doesn't change the other container.

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.