JavaScript-Copying Contents in primitive and non-primitive data types
Before talking about how copying works for each of the data types, let us understand what comes under primitive and non-primitive data types.
Primitive Datatypes:
A primitive data type contains data that is not an object and has no methods.
There are 6 primitive data types: string, number, bigint, boolean, undefined and symbol. Primitives are immutable.
Non-Primitive Datatypes:
A non-primitive data type contains objects. They can also be called as reference types as they are compared by reference instead of values.
Now, let us understand how copying works in both primitive and non-primitive data types.
let str1 = “Hello”;
let str2 = str1;
Here str1 is a primitive data type. Assume ‘Hello’ is written in a piece of paper and is held by str1 variable. Now when we write str2 = str1, what happens is that ‘Hello’ is written in another piece of paper and handed over to str2 variable. So, there are 2 pieces of paper containing ‘Hello’ each held by str1 and str2. I hope you get the analogy!
So, any changes made in one paper is not reflected in the other paper.
Now, str2 = “Hi” will change the value of str2 alone and not str1.
When it comes to non-primitive data types, copying happens differently.
let arr1 = [1, 2, 3];
let arr2 = arr1;
Let me explain the concept with the same analogy. Assume [1, 2, 3] is written in a notebook on page 1. Now, arr1 will have a piece of paper containing page 1(which is the address of [1, 2, 3]).
Now, when we write arr2 = arr1, arr2 will have a piece of paper containing page 1(which is the address of [1, 2, 3]).
So, when we change the array [1, 2, 3] to say, [1, 2, 4], both arr1 and arr2 will be affected as both variables hold the same address of the value.
If you want to know how to copy non-primitive data types by value, please check out my article, https://balasr97.medium.com/javascript-copying-composite-data-types-by-value-f9f4fa52875d