Rico Kahler
Rico Kahler

Reputation: 19242

What happens when I `Object.assign` to a primitive type in javascript?

I discovered that you can call Object.assign on a string or number type in javascript to get a sort of 'enhanced' primitive type.

// closure used to create object for simplicity
function makeObj() {

    let value = 6;

    let enhancedValue = Object.assign(value, {
        set: () => 'from the set method'
    })

    return {
        someValue: enhancedValue
    };
}

let myObj = makeObj();

// output is from nodejs

console.log(myObj.someValue); // accessing
// outputs: `{ [Number: 6] set: [Function: set] }`
console.log(myObj.someValue + 3); // using
// outputs: `9`
console.log(myObj.someValue.set()) // using method
// outputs: `from the set method`

So my question is: what type is this now? Is there any spec defining this behavior? Is there any reason not to do this? Could you explain what's going on here?

Upvotes: 4

Views: 3592

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074475

In JavaScript, almost all primitive types have an equivalent object type. So while "x" is a string primitive, new String("x") is a String object. Similarly, there are number primitives and Number objects, and boolean primitives and Boolean objects, etc.

The first step of Object.assign is to take the first argument and use the abstract ToObject operation on it, which performs that primitive-to-object step. From that point forward, it uses the object returned by ToObject. (ToObject just returns its argument if it's already an object.)

That object is what assign ultimately returns.

Upvotes: 4

Related Questions