I don't understand the 'Primitives will be wrapped to objects' part of example.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Primitives_will_be_wrapped_to_objects
The example shows that the primitives will be wrapped, but the result is an empty object.
var v1 = true;
var v2 = 10;
var v3 = Symbol('foo');
console.log(Object.assign({}, v1, v2, v3)); //ouput: {}
Is the result because primitives are ignored like null and undefined?
What does this example mean?
Yes, every parameter past the first will be converted to an object, but primitives do not have any enumerable own-properties by default:
- Let from be ToObject(nextSource).
- Let keys be from.[OwnPropertyKeys].
- (iterate over keys, assign them to the first argument object)
(The properties you can access on some primitives are either on the prototype, and not own keys (like toFixed
) or non-enumerable (like length
), so they don't get included)
So, the resulting object has no key-value pairs, because neither the boolean, the string, nor the symbol had any enumerable own-properties.
If you explicitly used new <primitiveType>
and assigned a property to the resulting wrapped object, you would see the property in the result:
var v1 = new Boolean(true); // please don't ever do this in real code
v1.foo = 'foo';
var v2 = 10;
var v3 = Symbol('foo');
console.log(Object.assign({}, v1, v2, v3));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With