Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 931
Rico Kahler Avatar asked Aug 31 '25 05:08

Rico Kahler


1 Answers

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.

like image 119
T.J. Crowder Avatar answered Sep 02 '25 19:09

T.J. Crowder