5

If a string literal is passed to Object.assign(), it will create an object having multiple keys like this example:

var v1 = 'myTest';
var obj = Object.assign({}, v1);
console.log(obj);

What is the reason behind that, instead of returning {0:'myTest'}?

Shidersz
  • 16,846
  • 2
  • 23
  • 48
brk
  • 48,835
  • 10
  • 56
  • 78
  • Imagine if you have a long list of keys and values.. It would be better to do it dynamically. The use cases of `Object.assign()` is endless – wentjun Apr 11 '19 at 18:08
  • 1
    `Object.assign` loops through every enumerable key, and the enumerable keys of `v1` are `v1[0]==="m"`, `v1[1]==="Y"`, etc. Perhaps you meant `v1 = ['myTest']`? – p.s.w.g Apr 11 '19 at 18:10
  • 2
    Because strings are iterable and have length... try `new Set('myTest')` – charlietfl Apr 11 '19 at 18:10
  • Where do you expect the `0` to come from, if the property value was `v1`? – Bergi Apr 11 '19 at 18:52

2 Answers2

5

From the MDN

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

So, the string literal v1 will be coerced to an object for the method to work. When the string literal is coerced to an object, the String() constructor is used, and you will get an object with numeric-properties, something array-like (object with a length property and indexed elements), but not an array, i.e, actually the same as if you do new String(v1):

let v1 = "myString";
let obj = new String(v1);
console.log(obj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

You don't get an Array:

Just for clarification, the coerced object you get from the string literal is an array-like object but not an array, as you can see on next test that uses Array.isArray() to do the check:

let v1 = "myString";

let strObj = new String(v1);
console.log(Array.isArray(strObj));

let arr = v1.split("");
console.log(Array.isArray(arr));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

For know more about array-like objects and differences to arrays, maybe you could give a read to next link:

JavaScript - Difference between Array and Array-like object

Shidersz
  • 16,846
  • 2
  • 23
  • 48
-1

The string acts like an array of characters, so you get a result similar to the following

var o = Object.assign({}, ['m','y','s','t','r','i','n','g'])

console.log(o)
dbramwell
  • 1,298
  • 6
  • 11