Help with understanding Object.assign

Can someone please explain what is happening in this code from Mozilla’s site. Where are these properties on the new object coming from?

const v1 = 'abc';

const v2 = true;

const v3 = 10;

const v4 = Symbol('foo');

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" }

It’s the string ‘abc’ and its enumerable properties (you can index into a string).

So the property key is the string index and the value is the actual string value. The other values shown are ignored.

Object('abc')
// String {"abc"}
// 0: "a"
// 1: "b"
// 2: "c"

'abc'.hasOwnProperty(0)
// true

'abc'[0]
// "a"

'abc'.hasOwnProperty(3)
// false

'abc'[3]
// undefined


Object(10)
// Number {10}

Number(10).hasOwnProperty(0)
false

1[0]
// undefined


var targetObj = {}

Object.assign(targetObj, 10)
// {}

Object.assign(targetObj, true)
// {}

Object.assign(targetObj, Symbol('foo'))
// {}

Object.assign(targetObj, 'abc')
// {0: "a", 1: "b", 2: "c"}
1 Like

Oh wow, that went over my head. Thanks for that