Deep vs Shallow Copy

Video

JavaScript Notes

JavaScript
    let shallowArr = [123,
                    'bob', 
                    true, 
                    null,
                    undefined];
    
    let deepArr = [123,
                'bob',
                true,
                ['Hank', 'Brent', 'Lacy'],
                {'Rouleau': 'Dog River', 
                'Wilcox': 'Wollerton'}
                ];
    
    let deepObj = {
                'characters': ['Wanda', 'Davis', 'Emma', 'Karen'],
                'places': ['Corner Gas', 'Ruby', 'Foo Mart'], 
                'grad68': false,
                'seasons': 5
    }
    
    // shallow copy
    let newObj = {...deepObj};	            // creates a shallow copy

    newObj.places[0] = "Ottawa";	        // changed inside the ref.
    console.log(newObj, deepObj);	        // both will show “Ottawa”

    newObj.places = ['Ottawa', 'Calcutta']	// new ref. created - only newObj is changed

    /******************************** 
    Deep Copy Method examples
    1. JSON.parse(JSON.stringify())
    2. Service Workers postMessage() onmessage 
    3. History API history.pushState(obj, title) history.state
    4. Notification API new Notfication("title", {data: obj}).data
    5. Build a custom recursive function
    *********************************/

    // deep copy
    let otherObj = JSON.parse(JSON.stringify(deepObj))	// creates a deep copy
    
    /******************************** 
    Shallow Copy Method examples
    1.	arr1.slice(0)
    2.	[ ].concat(arr1)
    3.	Spread Operator
    4.	Object.create( { }, obj)
    5.	Object.assign( { }, obj)
    6.	Array.from(arr1)
    *********************************/
    
    let s = 'steve';
    let g = s;
    s = 'new value';
    console.log(s, g);	                // s is ‘new value’, and g is ‘steve’

    let arr = shallowArr;	            // passes by reference, unless you use arr=Array.from(shallowArr)
    let arr1 = [...shallowArr];	        // use of the spread operator makes a shallow copy of the array shallowArr[0] = 456;
    console.log(arr, shallowArr);	    // both arr and shallowArr are the same