Object Spread Operator | Cloning Object in Javascript

For cloning Javascript objects you can use following code,
var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
A new term has been introduced the Object Spread Operator. It's not yet an official part of the language, but it did just recently reach Stage 3 proposal status, so it'll probably become official in ES2017 or ES2018. If you happen to be using the Create-React-App tool, that has the object spread Babel plugin already enabled.
var player = {score: 1, name: 'Jeff'};
var data=  {...player};
console.log(data); //{score: 1, name: 'Jeff'}
You can also change properties while assigning copy too using this operator. For eg,
var player = {score: 1, name: 'Jeff'};
var data=  {...player, name:"John"};
console.log(data); //{score: 1, name: 'John'}

Share this post