Search code examples
javascriptvariablesecmascript-6cloneimmutability

Is this a valid/safe way to clone any object/function/etc. in ES6?


I'm wondering whether this is a safe approach to cloning a variable that could be anything:

// the original variable definition:
let varIWantToCopy = 'hello world'

// the clone variable's definition:
let {varIWantToCopy: cloneOfVarIWantToCopy} = {varIWantToCopy}

// mutating the original value:
varIWantToCopy = 'goodbye world'

// should log out 'hello world':
console.log(cloneOfVarIWantToCopy)

Thank you for taking the time to look this over.

Kind regards,

Harry


Solution

  • I think you should use lodash if you really want to clone an object. There are several clone functions in lodash that you can use depending on your requirements.

    // or you can use lodash/clone
    import cloneDeep from 'lodash/cloneDeep';
    
    var objects = [{ 'a': 1 }, { 'b': 2 }];
    
    var cloned = cloneDeep(objects);
    
    console.log(cloned[0] === objects[0]); // this will be false
    

    So if you change the value of cloned[0], the value of object[0] won't change.