The _.clone() function is used to create a shallow copy of the given object. The nested objects or arrays will be copied using reference, not duplicated.
Syntax:
_.clone( object )
Parameters: This function accept a single parameter as mentioned above and described below:
- object: It contains the value of object that need to be copied.
Return Value: It returns the shallow-copy of the given object.
Below example illustrate the _.clone() function in Underscore.js:
Example 1:
<!DOCTYPE html> < html > Â Â < head > Â Â Â Â < script type = "text/javascript" src = Â Â Â Â </ script > </ head > Â Â < body > Â Â Â Â < script type = "text/javascript" > Â Â Â Â Â Â Â Â Â Â var info = { Â Â Â Â Â Â Â Â Â Â Â Â Company: 'neveropen', Â Â Â Â Â Â Â Â Â Â Â Â Address: 'Noida', Â Â Â Â Â Â Â Â Â Â Â Â Contact: '+91 9876543210' Â Â Â Â Â Â Â Â }; Â Â Â Â Â Â Â Â Â Â console.log(_.clone(info)); Â Â Â Â </ script > </ body > Â Â </ html > |
Output:
Example 2:
<!DOCTYPE html> < html > Â Â < head > Â Â Â Â < script type = "text/javascript" src = Â Â Â Â </ script > </ head > Â Â < body > Â Â Â Â < script type = "text/javascript" > Â Â Â Â Â Â Â Â Â Â var clon = _.clone({ Â Â Â Â Â Â Â Â Â Â Â Â Name: 'Ashok', Â Â Â Â Â Â Â Â Â Â Â Â Age: 32, Â Â Â Â Â Â Â Â Â Â Â Â Email: 'ashok@gfg.com' Â Â Â Â Â Â Â Â }); Â Â Â Â Â Â Â Â Â Â console.log(clon); Â Â Â Â </ script > </ body > Â Â </ html > |
Output: