Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I use primitives for Object.assign(), the results are presented as empty objects

Tags:

javascript

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?

like image 992
Sophia Avatar asked Apr 05 '19 10:04

Sophia


1 Answers

Yes, every parameter past the first will be converted to an object, but primitives do not have any enumerable own-properties by default:

  1. Let from be ToObject(nextSource).
  2. Let keys be from.[OwnPropertyKeys].
  3. (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));
like image 146
CertainPerformance Avatar answered Sep 18 '22 05:09

CertainPerformance