source: unsplash

How do you copy by value a composite data type?

Kashish Yadav
2 min readNov 15, 2020

--

In JavaScript, the data types are categorized into three main types- 1.Primitive

2. Trivial

3. Composite

The primitive data types are Numbers, BigInt, Boolean and String. The trivial data types include “null” and “undefined”, whereas the composite data types involve “objects” such as arrays, methods/functions, etc.

Copy by value- If a primitive type is assigned to another variable, that variable now is said to contain primitive value.

For example:

var x = 10;
var y = ‘abc’;

x contains 10 and y contains ‘abc.

When we assign these variables to other variables using ‘=’, we copy the value to the new variable. Therefore they are copied by value. In the code below, variable “b” is assigned y’s value. When you log all the variables to the console, you get the below result. However, it should be noted that these exist as separate variables and that just the values are copied. These variables in no way are related to each other, they simply carry the same values.

var x = 10;
var y = 'abc';var a = x;
var b = y;console.log(x, y, a, b); // -> 10, 'abc', 10, 'abc'

Copy by reference- When an object, such as an array, is copied to another variable using the assignment operator “=, the address of the object is what’s copied over as if it were a primitive type, instead of the actual value. This is why objects are normally known to copied by reference than value.

Now, the important question — How do we copy a composite data type by value instead of reference? There are three ways to do this- using “Spread” operator ,by using “Object.assign” or by using JSON.stringify() and JSON.parse() methods

Spread operator- Let’s look at the example below to understand this better:

var a = [1,2,3];
var b= […a];
b[3] = 4;
console.log(a); //prints [1,2,3]
console.log(b);// prints [1,2,3,4]

The 3 little dots that we added while assigning variable b to the array a copies the array a to b by value than reference.

Object.assign-

var a = [1,2,3];
var b= Object.assign([],a)
b[3] = 4;
console.log(a);//prints [1,2,3]
console.log(b);// prints [1,2,3,4]

Here, we have used Object.assign property to assign a’s value to b (yes, it really is that simple!)

JSON.parse()/JSON.stringify-

JSON.parse() takes a JSON string and transforms
it into a JavaScript object and JSON.stringify() takes a JavaScript object and transforms it into a JSON string.

Let’s look at the example below-

var a = [1,2,3]
var b= JSON.parse(JSON.stringify(a));

console.log(a,b);//prints [1,2,3] [1,2,3]

Thank you for reading! :)

--

--