Benjamin Li Benjamin Li - 1 year ago 64
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download