deep copy shallow copy javascript code example
Example 1: 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 2: deep copy javascript
function copy(arr1, arr2) {
for (var i =0; i< arr1.length; i++) {
arr2[i] = arr1[i];
}
}
copy(arr1, arr2)
Example 3: shallow copy vs deep copy js
/*
Search Results
Featured snippet from the web
A deep copy means that all of the values of the new variable
are copied and disconnected from the original variable.
A shallow copy means that certain (sub-)values are still connected
to the original variable. To really understand copying,
you have to get into how JavaScript stores values
/*
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;
}