Benjamin Li Benjamin Li - 10 months ago 46
Javascript Question

Which one is a better way to copy an object in javascript

currently I am using two ways to copy an object:
the first one is

let obj2 = {...obj}

the second one is

let obj2 = Object.assign({}, obj)

which one should be the recommended one? thanks

Answer Source

Assuming you're compiling with Babel, they are basically the same:

var a = {...b};

Compiles into:

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (, key)) { target[key] = source[key]; } } } return target; };

var a = _extends({}, b);

I suppose the object spread syntax is slightly better since it will still work if your environment doesn't support Object.assign.