I have a question about Object.assign()
.
const v1 = 'abc';
const v2 = true;
const v3 = 10;
const v4 = Symbol('foo');
//Primitives will be wrapped to objects
const obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
// Primitives will be wrapped, null and undefined will be ignored.
// Note, only string wrappers can have own enumerable properties.
console.log(obj); // { "0": "a", "1": "b", "2": "c" }
The output is just { "0": "a", "1": "b", "2": "c" }
. I guess this is the result of "abc"
being wrapped to an object.
Comment says null
and undefined
are ignored so they are not in the output.
But what of v2
, v3
, and v4
? They are not present in the output so I wonder what they become if wrapped to objects.
Can you explain why only { "0": "a", "1": "b", "2": "c" }
is in the output? I'm guessing this is because wrappers of true
and 10
and Symbol('foo')
have no own enumerable properties. Am I on the right track?
Thanks.
Yes, your assumption is correct. Strings have enumerable properties while booleans, numbers, and symbols do not. According to MDN
:
The Object.assign() method only copies enumerable and own properties from a source object to a target object.