JavaScript | How to copy by value a composite datatype ?
Data types basically specify what kind of data can be stored and manipulated within a program.There are six basic data types in JavaScript which can be divided into three main categories:
- Primitive datatype — String , Number, BigInt — copy by value
- Trivial datatype — Null , Undefined
- composite datatype — Object , Array, Function()— copy by reference
Copy by value — example
Here, variable a and b is assigned to 10 and 20 respectively, the value of b is assigned to variable c. Now if we override the value of b, the old value b which is assigned to c will not change
Copy by reference — example
Copy by reference refers to composite datatype, so an array is assigned to the variable a and a is assigned to variable b. If we add a new element in the array in var a, the array in a which is assigned to b will also get change because both variable a and b points to same location.
How to perform copy by value in composite datatype
There is way to perform copy by value in composite in composite datatype is by using Spread operator(…). It takes in an iterable (e.g an array) and expands it into individual elements.
The variable b has the elements of variable a array copied into it. Any changes made to a array will not be reflected in b array and vice versa.
If the simple assignment operator had been used then b would have been assigned a reference to a array and the changes made in one array would reflect in the other array.