1. If toString method exists and returns a primitive, then return it. Execution normally stops here, because toString exists on all objects by default.
2. If valueOf method exists and returns a primitive, then return it.
3. Otherwise, throw an exception.
Again, normally all objects have toString. Built-in objects have their own toString implementations:
alert( {key: 'value'} ) // toString for Objects outputs
alert( [1,2] ) // toString for Arrays lists elements "1,2"
alert( new Date ) // toString for Dates outputs the date as a string
Custom toString
For our objects, we can implement a custom toString:
var user = {
firstName: 'John',
toString: function() {
return 'User ' + this.firstName} }
alert( user ) // User John
Custom valueOf example
The magic method valueOf can be customized, just like toString:
var room = {
num: 777,
valueOf: function() {
return this.num}}
alert( +room ) // 777
That’s different from most other programmer languages, But simple when you get it.
P.S. Actually, the conversion is a bit more sophisticated than described here. I’ve left out a good bit of complexity to concentrate on how it really works.
Objects String, Number, Boolean
Objects in JavaScript can be converted to primitives in three contexts: