/    /  Javascript copy

Javascript copy

 

3 Ways to Copy Objects in JavaScript:

 

Use the spread (…) syntax
Use the Object.assign() method
Use the JSON.stringify() and JSON.parse() methods

 

copy an object using three methods above:

 

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));

 

Both javascript spread (…) and Object.assign() return a shallow copy otherwise the JSON methods carry a deep copy.

 

Shallow copy vs. deep copy:

 

In JavaScript, we use variables to store values that can be primitive or references. When we make a copy of a value stored in a variable, and we create or generate a new variable with the same value. For a primitive value, you just simply provide a simple assignment:

 

let counter = 1;
let copiedCounter = counter;

 

copied variable:

 

copiedCounter = 2;
console.log(counter);

 

OUTPUT:

 

1