shallow and deep copy in 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: 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: best way to clone an object in javascript
const person = {
firstName: 'John',
lastName: 'Doe'
};
// using spread ...
let p1 = {
...person
};
// using Object.assign() method
let p2 = Object.assign({}, person);
// using JSON
let p3 = JSON.parse(JSON.stringify(person));