How to copy by value a composite data type in JS?
“DATA TYPES” in JS
Types of data types in JS:
- Primitive data type
- composite data type
- Special data type
Data types like numbers, strings, boolean are some of the primitive types.
var a=10; //numbers
var a=”hello” //string
var a=true/false //boolean
Undefined and Null are special data types.
Copy by value and copy by reference:
Copy by value: In a primitive data-type when a variable is assigned a value we can imagine that a box is created in the memory. Inside the box, the value assigned to the variable is stored. Even after changing the content of the next variable the original variable remains the same.
Copy by reference:
In the case of a non-primitive data-type, the values are not directly copied. When a non-primitive data-type is assigned a value a box is created with a sticker of the name of the data-type. However, the values it is assigned is not stored directly in the box. The language itself assigns a different memory location to store the data. The address of this memory location is stored in the box created.
In the above example, we can observe the change of admin name leads to a change in the original value.
So now the question is how to copy by value a composite data type?
we have 5 types to copy by value a composite data type
- Using Array.map().
- Using spread operator(…)
- Using JSON.stringify() and JSON.parse() methods.
- Using Object.assign()
- Using Slice() method
This method will calls a provided
callbackfunction once for each element in an array, in order, and constructs a new array from the results.
Using spread operator(…)
Spread operator allows an iterable to expand in places where 0+ arguments are expected. It takes in an iterable (e.g an array) and expands it into individual elements. The spread operator is commonly used to make shallow copies of JS objects. Using this operator makes the code concise and enhances its readability.
Using JSON.stringify() and JSON.parse() method
Object.assign() method copies all enumerable(one by one)own property from one or more source objects to a target object. It returns the target object. It uses
[[Get]] on the source and
[[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.