by Angus Croll

JavaScript and valueOf

In JavaScript, valueOf and toString are sister methods inherited by every object. One of these methods will get invoked whenever an expression encounters a complex object where a primitive value was expected. For example :-

alert(myHamster);
var result = 2 + myHamster;

In broad terms, if the expression hints at the need for a string then toString is invoked, otherwise its valueOf . If either method returns a non–primitive, the other method gets a try. The above examples expected myHamster to be a string and a number respectively so they are evaluated as:-

Here, valueOf is returning a boolean, but the final run instructions use concatenation to coerce the booleans into numbers (1 for pass, 0 for failure).

In the right situation, overriding valueOf can be a useful tool. But even if you never use it in this way, knowing how and why JavaScript chooses between default toString and valueOf methods will help you to know your code better.

TPReal, that’s explained in ES5 – 8.12.8 “When the [[DefaultValue]] internal method of O is called with no hint, then it behaves as if the hint were Number, unless O is a Date object (see 15.9.6), in which case it behaves as if the hint were String.”