deep copy and shallow copy javascript code example

Example 1: copy object javascript

var x = {key: 'value'}
var y = JSON.parse(JSON.stringify(x))

//this method actually creates a reference-free version of the object, unlike the other methods
//If you do not use Dates, functions, undefined, regExp or Infinity within your object

Example 2: js shallow copy

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

Example 3: 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 4: deep copy javascript

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

Example 5: shallow clone

How to Execute Git Shallow Clone
Provide an argument of -- depth 1 to the git clone command to copy only the latest revision of a repo:

git clone -–depth [depth] [remote-url]
 

You can also use git shallow clone to access a single branch:

git clone [remote-url] --branch [name] --single-branch [folder]
 

With git shallow clone you get fewer files. And as a result, they clone faster. Builds and feedback can be delivered quicker.

Example 6: 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


/*