Difference between Lodash _.clone() method and ‘=’ operator to copy Objects
Last Updated :
08 Jun, 2021
In this article, we will learn about the difference between using the _.clone() method in Lodash and using the ‘=’ operator to copy objects. Both of these methods are used to create a copy of an object in JavaScript. However, both work in very different ways.
Using _.clone() Method: The _.clone() method creates a new object and copies each value from the original to the new object. This creates a shallow copy of the object. Any changes to the original object do not affect the object copied.
Syntax:
_.clone( object )
Parameters: This function accepts only one parameter which is the object that needs to be copied.
Return Value: It returns the shallow copy of the given object.
Example: The below example shows that changing the original object does not affect the object copied using the _.clone() function.
Javascript
const _ = require( "lodash" );
var originalflower = {
Name: "Rose" ,
color: "Red" ,
petal: 5,
};
var copyflower = _.clone(originalflower);
console.log( "Cloned object : " ,
copyflower);
originalflower.Name = "Red Rose" ;
console.log( "original flower: " ,
originalflower);
console.log( "copy flower: " , copyflower);
|
Output:
Cloned object : { Name: 'Rose', color: 'Red', petal: 5 }
original flower: { Name: 'Red Rose', color: 'Red', petal: 5 }
copy flower: { Name: 'Rose', color: 'Red', petal: 5 }
Using the ‘=’ operator for copying the object: In this approach, simply using the ‘=’ operator points the copied object to the original object that already exists. The changing of the original object does affect the object copied.
Example: The below example shows that changing the original object affects the object copied using the ‘=’ operator.
Javascript
const _ = require( "lodash" );
var originalFlower = {
Name: "Rose" ,
color: "Red" ,
petal: 5,
};
var copyFlower = originalFlower;
console.log( "Copy object : " ,
copyFlower);
originalFlower.Name = "Red Rose" ;
console.log( "The name of original flower is - " ,
originalFlower.Name);
console.log( "The name of copy flower is - " ,
copyFlower.Name);
|
Output:
Copy object : { Name: 'Rose', color: 'Red', petal: 5 }
The name of original flower is - Red Rose
The name of copy flower is - Red Rose
Share your thoughts in the comments
Please Login to comment...