Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptLodash _.clone() Method

Lodash _.clone() Method

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 } ]

Reference: https://lodash.com/docs/4.17.15#clone

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments