Open In App

Lodash _.clone() Method

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lodash _.clone() method is used to create a shallow copy of the value. This method supports cloning arrays, array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays. It is loosely based on the structured clone algorithm.

Syntax:

_.clone(value);

Parameter:

  • value: This parameter holds the value that needs to be cloned.

Return Value:

  • This method returns the shallow copy of the value.

Example 1: In this example, we have seen that we can clone an object and if we modify that original object there will be no effect on the cloned one because it is a new separate object in memory.

javascript
const _ = require('lodash');

let obj = {
    x: 23
};

// Shallow copy
let shallowCopy = _.clone(obj);

console.log('Comparing original with'
    + ' shallow ', obj === shallowCopy);

obj.x = 10; // Changing original value

console.log('After changing original value');
console.log("Original value ", obj);
console.log("Shallow Copy value ", shallowCopy);

Output:

Comparing original with shallow  false
After changing original value
Original value { x: 10 }
Shallow Copy value { x: 23 }

Example 2: In this exmaple, we have seen that after changing original value the shallow copy value also changed because _.clone() doesn't copy deeply it just passed the reference.

javascript
const _ = require('lodash');

let obj = [{ x: 1 }, { y: 2 }];

// Shallow copy
let shallowCopy = _.clone(obj);

console.log('Comparing original with shallow ',
    obj[0] === shallowCopy[0]);

// Changing original value
obj[0].x = 10;

// Values after changing original value
console.log("After changing original value");
console.log("Original value ", obj);
console.log("Shallow Copy value ", shallowCopy);

Output:

Comparing original with shallow  true
After changing original value
Original value [ { x: 10 }, { y: 2 } ]
Shallow Copy value [ { x: 10 }, { y: 2 } ]

Next Article

Similar Reads