Reputation: 1144
I am having troubles with implicit coercion with the + operator in JavaScript. Namely the priority order of valueOf and toString.
var obj = {};
obj.toString();
=> "[object Object]"
obj.valueOf();
=> Object {}
'Hello ' + obj;
=> "Hello [object Object]"
So obj is implicitly coerced to a string using the toString() method over valueOf();
var obj2 = {
toString: function() {
return "[object MyObject]";
},
valueOf: function() {
return 17;
}
};
obj2.toString();
=> "[object MyObject]"
obj2.valueOf();
=> 17
'Hello ' + obj2;
=> "Hello 17"
So when I override the toString and valueOf methods, the + operator will coerce with valueOf.
What am I missing? Thanks.
Upvotes: 3
Views: 672
Reputation: 10992
Just to make it more simpler to understand consider the following two cases -
var p = {};
//Case 1, here valueOf() method is called.
console.log(p); //Prints: Object {}
//Case 2, toString() method will be called.
console.log('the value of p is'+ p); //Prints: the value of p is[object Object]
So basically it depends on the way you are using this object.
Upvotes: 0
Reputation: 2710
The answer can be found in a similar thread: valueOf() vs. toString() in Javascript
If the object can be transformed into a "primitive" JavaScript will try to treat it as a number. Otherwise string concatenation via the toString
method is used. Without the valueOf
method, JavaScript cannot tell how to convert the data, hence the object will be concatenated as a string.
If you're interested the precise specifications are available in the following pdf at around page 58: http://www.webreference.com/javascript/reference/ECMA-262/E262-3.pdf
Hope that helped :-)
Upvotes: 5