title: valueOf() vs. toString() in Javascript
body: <p>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().</p>
  
  <p>For example, the code</p>
  
  <pre><code>var x = {toString: function() {return "foo"; },
           valueOf: function() {return 42; }};
  window.console.log ("x="+x);
  window.console.log ("x="+x.toString());
  </code></pre>
  
  <p>will print</p>
  
  <pre><code>x=42
  x=foo
  </code></pre>
  
  <p>This strikes me as backwards .. if x were a complex number, for example, I would want valueOf() to give me its magnitude, 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.</p>
  
  <p>Is this just the way it is? </p>