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:-

alert(myHamster.toString()); //interpreter expected a string
var result = 2 + myHamster.valueOf(); //expected a number

Continue reading