Yash Khankhoje
2 min readDec 13, 2020

--

Copy by value a composite data type in JavaScript

here are two methods in javascript to copy composite data.

1) Copy by Value

2) Copy by Reference

Although copy by reference is better option to copy composite data as it works on location of data instead of working on exact data. But in this blog we will have a look on “ Copy by methods”.

There are three ways to perform copy by values on composite data types. Those are as follows.:

1) Using the JSON.stringify() and JSON.parse() methods

2) Using the Object.assign() method

3) Using the spread (…) operator

1) Using the JSON.stringify() and JSON.parse() methods:

The JSON object is available in all modern browsers those has two useful methods to deal with JSON-formatted content: parse and stringify. JSON.parse(). It takes a JSON string and transforms it into a JavaScript object. JSON.stringify() takes a JavaScript object and transforms it into a JSON string. It works as follows.

Using the JSON.stringify() and JSON.parse() methods
Output

2) Using Object.assign():

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

Using Object.assign()
Output

3) Using the spread (…) operator:

The spread operator (…) is from modern JavaScript (ES6 and higher) that can be used to clone an array by “spreading” its elements.Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array.Using spread will clone your object. Note this will be a shallow copy.

Using the spread (…) operator
Output

--

--

Yash Khankhoje

Software developer at KC Overseas. Highly passionated programmer and happy to learnd and teach new technologies.