Shallow Cloning - Please Explain

HI guys was wondering if someone could explain shallow cloning . slice as I cant get my head around it

what is the difference between the following code.

 let cheat  = [1, 2, 3, 4]
let newCheat = cheat;

newCheat
output is [1,2,3,4]

as opposed to the shallowclone

let cheat = [1,2,3,4]
newCheat = cheat.slice();

newCheat
output is still the same
[1,2,3,4]

so just wondering why we would put the .slice in there when the output is the same

Thank you (-:

Objects and Array in JavaScript are reference types, a reference type is a code object that is not stored directly where it is created, but that acts as a kind of pointer to a value stored elsewhere. So when we copy an object or an array we copy the pointer not the actual value.


A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made. As a result, when you change either the source or the copy, you may also cause the other object to change too — and so, you may end up unintentionally causing changes to the source or copy that you don’t expect.

Here slice create a new array, by deep copy the value of the array. So changing value in the copy won’t affect the original array.
here is https://www.youtube.com/watch?v=9ooYYRLdg_g a video it will help you to understand the differences

1 Like