JavaScript Object to Primitive Conversion
Tags: javascript, node, tutorial, webdev
Published: 2021-02-22 19:46:27

[![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1613668162316/G1zfmhxQd.png)](https://www.cssigniter.com/members/aff/go/belloosagienoah)

---

### Type coercion - Objects to Primitives
Type coercion can also occur on objects when certain operations are done on them.

See the example below:

```js
const obj1 = { name: 'Peace', age: 18 };
const obj2 = { name: 'Bob', age: 10 };

const obj = obj1 + obj2;
// const obj = obj1 - obj2 // NaN number
console.log(obj, typeof obj)
// [object Object][object Object] string
```

See another example below:

```js
const date1 = new Date(2050, 04, 03);
const date2 = new Date(2040, 11, 06);

const delta = date1 - date2;
console.log(delta, typeof delta); // 296784000000 number
date1 > date2 // true
```

In the examples above, the object type is converted to the different data types.

---
### Type conversion - Objects to Primitives
Apart from objects auto-conversion to primitive,  conversion can be specified ourselves.

```js
const date1 = new Date(2050, 04, 03);
const date2 = new Date(2040, 11, 06);

const delta = date1 - date2;
// delta.valueOf() // 296784000000 => number
console.log(delta.toString, typeof delta); 
// [Function: toString] number
```

---
### *Symbol.toPrimitive*
The built-in symbol named `Symbol.toPrimitive` can specify the conversion on an object.

```js
obj[Symbol.toPrimitive] = function(hint) {
  // must return a primitive value
};
```

See the example below:

```js
const user = {
  name: "Bello",
  money: 4000,

  [Symbol.toPrimitive](hint) {
    console.log(`hint: ${hint}`);
    return hint == "string" ? `{name: "${this.name}"}` : this.money;
  }
};

// conversions
console.log(user); 
/*
{
  name: 'Bello',
  money: 4000,
  [Symbol(Symbol.toPrimitive)]: [Function: [Symbol.toPrimitive]]
}
*/
 
console.log(+user); 
/*
hint: number
4000
*/

console.log(user + 500); 
/*
hint: number
4500
*/
```

In the example above, the method `user[Symbol.toPrimitive]` handles all the conversion.

---

[![Whogohost.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1614039291707/NsVXnnTES.png)](https://www.whogohost.com/host/aff.php?aff=7390&page=hosting)

---

### **toString** and **valueOf** methods

Instead of the `Symbol.toPrimitive` method to handle all conversions, we can use the `toString()` and `valueOf()` methods.

A little adjustment is made to the example above. 

See the example below:

```js
const user = {
  name: "Bello",
  money: 4000,

  toString() {
    return `{name: "${this.name}"}`;
  },

  valueOf() {
    return this.money;
  }
};

// conversions
console.log(user); 
/*
{
  name: 'Bello',
  money: 4000,
  toString: [Function: toString],
  valueOf: [Function: valueOf]
}
*/

console.log(+user); // 4000
console.log(user + 500); // 4500
``` 

Below is another example:

```js
const obj = {
  // toString handles all conversions in the absence of other methods
  toString() {
    return "10"; // string
  }
};

const toNum = obj * 4;
console.log(toNum, typeof toNum); // 44 number 
// * converted 10 in string to 44 in number
```

See another example below:

```js
const obj = {
  // toString handles all conversions in the absence of other methods
  toString() {
    return "10";
  }
};

const str = obj + 4;
console.log(str, typeof str); // 104 string 
// + concatenate 10 and 4 to give a string
```

---
[![Buy me a Coffee](https://res.cloudinary.com/bizstak/image/upload/v1610317510/ko-fi-trans_fr3su4.png)](https://www.buymeacoffee.com/techstackmedia)

---

[![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yx1zjy04hmx9k2y3i1qu.png)](https://www.travelstart.com.ng/?affId=217135&utm_source=affiliate&utm_medium=217135)