js create a copy of an object code example

Example 1: clone object in js

var student = {name: "Rahul", age: "16", hobby: "football"};

//using ES6
var studentCopy1 = Object.assign({}, student);
//using spread syntax
var studentCopy2 = {...student}; 
//Fast cloning with data loss
var studentCopy3 = JSON.parse(JSON.stringify(student));

Example 2: copy object javascript

var x = {myProp: "value"};
var y = Object.assign({}, x);

Example 3: copy object javascript

// es6
const obj = {name: 'john', surname: 'smith'};
const objCopy = {...obj};