valueOf() vs. toString() in Javascript

Posted by brainjam on Stack Overflow See other posts from Stack Overflow or by brainjam
Published on 2010-03-21T02:25:36Z Indexed on 2010/03/21 2:31 UTC
Read the original article Hit count: 385

Filed under:

In Javascript every object has a valueOf() and toString() method. I would have thought that the toString() method got invoked whenever a string conversion is called for, but apparently it is trumped by valueOf().

For example, the code

var x = {toString: function() {return "foo"; },
         valueOf: function() {return 42; }};
window.console.log ("x="+x);
window.console.log ("x="+x.toString());

will print

x=42
x=foo

This strikes me as backwards .. if x were a complex number, for example, I would want valueOf() to give me its magnitude (so that zero would become special), but whenever I wanted to convert to a string I would want something like "a+bi". And I wouldn't want to have to call toString() explicitly in contexts that implied a string.

Is this just the way it is?

© Stack Overflow or respective owner

Related posts about JavaScript