Why does the following snippet return { a: 3, b: undefined }
and not { a: 3, b: 2 }
?
console.log(Object.assign({ a: 1, b: 2 }, { a: 3, b: undefined }));
This question asks about a function that gives the latter output instead of the former, but my question is why was Object.assign()
designed this way? Or to put it a different way, what exactly are the differences between { a: 3 }
and { a: 3, b: undefined }
?
UPDATE (from the comments on apsillers answer):
{ a: 1 }
says "I have no property named 'b'", { a: 1, b: undefined }
says "I have a property 'b' but it has not yet been given a value", and { a: 1, b: null }
says "I have a property 'b' that should hold an object but has not yet been given an object to hold". Since in the latter two the object has a property 'b', regardless of what the value is, it will still override non-null non-undefined values when passed into Object.assign()
.