Reputation:
I would like to know the difference between this:
Object.assign(otherObject, {
someNewProperty: ''
});
and
otherObject.someNewProperty = '';
And.. which one is faster?
Thanks.
Upvotes: 27
Views: 11066
Reputation: 315
This is actually a good question: We just found a bug, where we would assign properties to a file using Object.assign.
const file = new File(["foo"], "foo.txt", {
type: "text/plain",
});
file.name='test'; // does not update the readonly value but doesn't return an error
Object.assign(file,{name:'test'}); // error: 'Cannot set property name of #<File> which has only a getter'
Upvotes: 0
Reputation: 233
For single property, direct assignment (otherObject.someNewProperty = ''
) is twice faster, but for multiple values - time will grow. Each property + 5% to 10%. Also, code-wise Object.assign
is nicer for multiple options.
Object.assign(otherObject, {
prop1: '',
prop2: '',
prop3: '',
...
});
VS
otherObject.prop1 = '';
otherObject.prop2 = '';
otherObject.prop3 = '';
...
You simply can run Profiles tab in Chrome Development tool and run few tests.
Upvotes: 9
Reputation: 78
There is another important thing to show here about the differences between assign directly and using Object.assign(actually, not exactly a difference, but a important thing to be aware).
If you have a Object that's assigned to another variable in JS, like this:
const a = { a: 1 }
const b = a
then, you decided to use Object.assign to change the value in a
and assign to another variable(d
), you will change the value in b
as well(even you not assigning the Object.assign return to a
, in this example let's assign to a new variable d
).
const d = Object.assign(a, { a: 2 })
console.log(a) // { a: 2 }
console.log(b) // { a: 2 }
console.log(d) // { a: 2 }
Basically, it's important to know that Object.assign will mutate the target object as well all variables pointing to it.
Now, if you use directly the assignment to d
, it'll not change the value in a
(and in b
as well will not change).
const d = { ...a, ...{ a: 2 }}
console.log(a) // { a: 1 }
console.log(b) // { a: 1 }
console.log(d) // { a: 2 }
Upvotes: 1
Reputation: 11707
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Whereas otherObject.someNewProperty = '';
is a method to directly assign a value to some property of an object.
Obviously the Object.assign
pattern is much slower : jsperf.com/assign-vs-equals
Upvotes: 19
Reputation: 46323
Object.assign()
is a pretty versatile function that is designed to do complex object composition.
The property dot notation is a straight forward way to assign a single value to a single property.
Regarding which is faster, that's irrelevant considering these are not equivalent, and as one of my all time favorite posts noted "asking which one runs faster is maybe a non-starter".
Upvotes: 2