javascript deep copy and shallow copy code example

Example 1: js shallow copy

Object.assign({}, obj); // ES6 shallow copy

Example 2: javascript '=' operator shallow copy or deep copy

// The '=' operator in javascript can serve the purpose of shallow vs
// deep copy.

// The '=' operator in javascript will assign deep copy to primitive 
// data types. For example:
let a = 10;
let b = a;
b = 4;
console.log(a);
// Output: 10
console.log(b);
// Output: 4


// The '=' operator in javascript will assign shallow copies to
// non-primitive data types. For example:
let a = ['a','b','c','d','e','f','g'];
let b = a;
b.pop();
console.log(a);
// Output: ["a","b","c","d","e","f"]
console.log(b);
// Output: ["a","b","c","d","e","f"]

Example 3: deep copy javascript

function copy(arr1, arr2) {
	for (var i =0; i< arr1.length; i++) {
    	arr2[i] = arr1[i];
    }
}
copy(arr1, arr2)

Example 4: deep copy js

//recursive deep copy of object
function dup(o) {
    // "string", number, boolean
    if(typeof(o) != "object") {
        return o;
    }
    
     // null
    if(!o) {
        return o; // null
    }
    
    var r = (o instanceof Array) ? [] : {};
    for(var i in o) {
        if(o.hasOwnProperty(i)) {
            r[i] = dup(o[i]);
        }
    }
    return r;
}