All JavaScript objects, either custom or built-ins, inherit the valueOf method from Object. JavaScript automatically calls the valueOf method when an object is required to be converted to a primitive type. Although the default implementation of valueOf returns the object itself, it can be overridden to return a primitive value.
Let's take an example. The Percentage is a constructor function and its valueOf method is overridden:
function Percentage( v ) {
this.value = v;
}
// Override valueOf method
Percentage.prototype.valueOf = function() {
return this.value/100;
};
What is the result of adding an instance of Percentage to a primitive number as shown below?
console.log( new Percentage( 40 ) + 1 );