Projects > JS References vs Clone

Home Projects Challenges

JS References vs Clone


June 14, 2021 | Vanilla JS

Normal data type

        
        let firstNum = 10;
        let secondNum = firstNum;
        firstNum++;
        console.log(firstNum, secondNum);
      
      

In case of normal data type such as string, number, boolean, when we give a reference to the other variable. The other variable will just take the value. So whenever we change the first variable, it doesn't affect the other one.


Array and Objects

        
        let num = [4, 5, 1];
        let copyNum = num;
        num.push(5);
        console.log(num, copyNum);
        
      

In case of array and objects, when you assign an variable to another reference. It will link that object reference. So whenever you make change to the first one, whether you call the first and the second variable, it refers to the same object. In which result in such the same output


Several ways to clone an array and objects

        
          let num = [4, 5, 1];
          let copyNum = [...num];
          let num2 = [...num, data, data];
          let num3 = num.splice();
          let num4 = [].concat(num);
      
      

There are many way that we can clone an array, ... in which also known as spread operator is very useful and fast in this regard


        
        let obj = {
          'nickname': 'chanrose',
          'gamename': 'blubu',
        }
        let obj1 = Object.assign({}, obj);
        let obj2 = Object.assign({}, obj, {'newproperty': 'newvalue'});
        let newObj = JSON.parse(JSON.stringify(obj));
      
      

The disadvantage of copying objects with assign, it only copies the current level but not the deep or next one (it will be the same reference). But anyway, the obj1 is purely for copying the object, obj2, copying and assign more new property inside it. JSON seems like not very direct way but it works great for even those in the deeper level.


↤ Go Back

Updated in June 14, 2021
Gmail | Proton | LinkedIn | Github
Alright reserved 2021