I want to give you a test, so you get the real reason you need to learn about Deep and shallow clone or copy and why we still need to have the understanding of immutable and mutability in JavaScript ready let’s go 😎
In previous article I discussed about mutability and immutability in JavaScript, if you’ve read the article kudus to you and if you haven’t, please check it out immutability and mutability in JavaScript because in this article I will be assuming you understand the concept of immutability and mutability in JavaScript and for those who have read it,
can you figure the output of the following snippet:
const fruits = ['apple', 'mango', 'banana']
const fruitsAndVeg = ['pinapple', 'peaches',['dodo', 'tomato' ]]
const fruitsCopy = [...fruits];
const fruitsAndVegCopy = [...fruitsAndVegCopy]
what will happen if we then console the above snippet 👇🏿:
fruitsAndVegCopy[2].push("potatoes");
console.log(fruitsAndVegCopy) // ?
console.log(fruitsAndVeg) // ?
Oh! and don’t focus on the potatoes I don’t know if they are in the category of vegetable but let’s take it as it is, so the question is what do you think the output will look like?
well, the output will look something like this:
console.log(fruitsAndVegCopy) // ['pinapple', 'peaches',['dodo', 'tomato', 'potatoes']]
console.log(fruitsAndVeg) // ['pinapple', 'peaches',['dodo', 'tomato', 'potatoes']]
if you guessed it correct well good for you, but do you know why? and if you guessed wrong well 😴 you will need to stay with me for a while
you may be confused what in the hell is this I get it I have been there too.
it all boils down on how non-primitive datatypes are stored in JavaScript, non-primitive data types in JavaScript include arrays, objects, functions.
Heap and storage of non-primitive types in memory
when you create a non-primitive datatype in JavaScript it is stored in a memory location called heap and the variable name you’ve given that non-primitive will be used to identify the data you’ve stored in heap by their memory address in heap.
let’s demonstrate how it works in the below snippet
const arrOne = [1,2,3,4,5];
const arrTwo = [6,7,8,9,0];
const arrThree = ['a', 'b', 'c'];
The diagram below shows how the arrays created will be stored in memory:
In the diagram the heap is the container for our arrays actual data.
The actual variable we’ve created stores reference pointing to a place in heap memory where our arrays are being stored and (this also applies to objects and function, ), which means the variable will store the reference of a place in memory to find the data not the actual data.
Shallow copy:
We say that something is shallow copied when we have a nested non-primitive like object of arrays or arrays of object or nested arrays as the example we had before
when we don’t want to mess with the original array or object and create a copy of it using the spread operator like we had in this example
const fruitsAndVeg = ['pinapple', 'peaches',['dodo', 'tomato' ]]
const fruitsAndVegCopy = [...fruitsAndVegCopy]
The values that are not arrays will be copied, because primitive stores actual values not the reference as non-primitives,
and since we have a nested array inside the original array it means we have that nested arrays reference to the memory not the actual array itself as it is in the code.
This is how it will be structured in the memory
Shallow copy can be defined as a copy that copies the top level and on the nested level it copies its memory reference, which will point to the same memory location but with different reference
the new copy will refer to the same location as the original one, this means if you change the fruitsAndVegCopy nested array contents, changes will also apply to the original array because they point or refer to the same location in memory on the same data
but if you change pineapple to apple of fruitsAndVegCopy array they won’t have effect on the original one.
Deep copy:
let’s also talk about Deep copy, Deep copy will copy the value from top-level to the deepest level of the object we want to clone.
I will be using the JSON method technique to show how to deep clone
JSON method technique:
- step 1: first
stringfythe object we are about to clone:
we use the stringfy() method of JSON to make the object a string
const fruits = ['apple', 'mango', 'banana'];
const fruitsAndVeg = ['pinapple', 'peaches',['dodo', 'tomato' ]];
const stringfiedarr = JSON.stringfy(fruitsAndVeg); // '["pinapple","peaches",["dodo","tomato"]]'
our new stringfied array version would look like this:
- step 2: Convert the object from a string version to a non-primitive type again:
the parse() method of JSON is used to convert back converted object back to normal objects or non-primitive type
and then store that array into a new variable which will create a new memory reference for our array
const fruits = ['apple', 'mango', 'banana'];
const fruitsAndVeg = ['pinapple', 'peaches',['dodo', 'tomato' ]];
const fruitAndVegCopy = JSON.parse(stringfiedObject)
after the conversion is done we will create a new memory location assign its address to fruitAndVegCopy which will be completely different from the original array allowing us to manipulate it without having to worry about the original array mutability
Final Thoughts:
if you find this way of deep clone or copy using JSON you can read more about this you can read more about the method to deep clone called structuredClone method which does the same as the JSON does
conclusion:
I hope you got something out of this and have grasped the concept of deep and shallow copy in JavaScript, I would appreciate sharing with me what you gained throughout this whole article and what do you think about the content in general.



Top comments (0)