What is the _.clone() method in Lodash?
Overview
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.
Syntax
_.clone(value)
Parameter
This method accepts the following parameter.
value: The value to be cloned
The following types can be used as the parameters:
- Objects
- Arrays
- Array buffers
- Typed arrays
- Sets
- Maps
- Booleans
- Strings
- Symbols
- Regex
- Date
Return value
This method returns the shallow copy of the original value.
Example
Let’s look at an example of the _.clone() method in the code snippet below:
Explanation
In the HTML tab:
- Line 5: We import the
lodashscript.
In the JavaScript tab:
- Lines 2 to 8: We create an object
valueto clone. - Line 11: We use the
_.clone()method to create a clone ofvalue. - Lines 14 to 15: We print the original and cloned values to the console.
- Line 18: We edit a top-level property of the original value.
- Lines 21 to 22: We print the original and cloned values to the console again.
- Line 25: We edit a nested property of the original value.
- Lines 28 to 29: We print the original and cloned values to the console again.
Output
- The
_.clone()method creates a clone of value. - The original and the cloned value have similar values.
After editing a top-level property of original value:
- The top-level properties are unique in both the values.
- Thus, the
nameattribute 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:
- The nested properties share reference addresses.
- Thus, the
number.homeattribute is updated only in both the values. It can be seen in the console.