Jaa


valueOf and toString

My colleague SDET Titus Chandramohan sent me a mail and reported a inconsistent bahavior in JScript. The issue he reported was...

 

var f = function(){ return 5;};
var num = new Number(5);
num.x = f.valueOf;

num.x(); ------> this should return 5 and it is doing as expected.

 

 

Now instead of valueOf, if we have toString then we get runtime error

 

var f = function(){ return 5;};
var num = new Number(5);
num.x = f.toString

num.x(); ----> this should return 5, but we are getting a runtime exception "function expected".

 

Well, he was expecting same behavior in both cases which was not happening due to following reason...

 

In runtime, Each builtin type has its own function for toString operation. That means there is a function for number (Let’s say JSNumberToString), for Boolean(Let’s say JSBooleanToString) and so on. These are all internal functions and not exposed.

When you do num.x = f.toString  the function which returns the string representation of a function object (JSFunctionToString ) is assigned to num.x. JSFunctionToString checks whether the object which it is being applied on, is of type function or not? If not then it throws the error you are getting. In above repro code, he was actually calling JSFunctionToString on a number object . JSFunctionToString finds that it is being called upon a Number object and throws the error.

The same logic holds true for valueOf also. But the difference is that the function type doesn’t have their own valueOf. They inherit it from their parent in prototype chain (Object). Since everything derives from Object in Jscript, the same valueOf works for number also.