The _.clone()
method in Lodash creates and returns the shallow copy of a value.
Shallow copy means that all the top-level properties of both the values (original and cloned) are unique, but the nested properties share the same reference address. Thus, modifying any original nested values will automatically modify the cloned nested value and vice versa.
_.clone(value)
This method accepts the following parameter.
value
: The value to be clonedThe following types can be used as the parameters:
This method returns the shallow copy of the original value.
Let’s look at an example of the _.clone()
method in the code snippet below:
In the HTML tab:
lodash
script.In the JavaScript tab:
value
to clone._.clone()
method to create a clone of value
._.clone()
method creates a clone of value.After editing a top-level property of original value:
name
attribute is updated only in the original value. The cloned value won’t get modified. It can be seen in the console.After editing a nested property of original value:
number.home
attribute is updated only in both the values. It can be seen in the console.