tags:

views:

106

answers:

3

Javascript has lot's of "tricks" around types and type conversions so I'm wondering if these 2 methods are the same or if there is some corner case that makes them different?

+9  A: 

value.toString() will cause an error if value is null. String(value) should not.

For example:

var value = null;
alert(value.toString());

will fail because value == null.

var value = null;
alert(String(value));

should display a message reading "null" (or similar), but it will not crash.

Jonathan
I've never seen a null pointer exception in javascript... where did you see that?
no
Maybe you meant a "`value` is null/undefined" error?
casablanca
nice. it would be yet nicer with an example
mykhal
@no, @casablanca Fixed. I'm used to Java. @mykhal How does that look?
Jonathan
A: 

String(value) should have the same result as value.toString() in every case, except for values without properties like null or undefined. ''+value will produce the same result.

no
+5  A: 

They are not completely the same, and actually, the String constructor called as a function (your first example), will at the end, call the toString method of the object passed, for example:

var o = { toString: function () { return "foo"; } };
String(o); // "foo"

On the other hand, if an identifier refers to null or undefined, you can't use obviously the toString method, it will give you a TypeError exception:

var value = null;
String(null); //       "null"
value.toString(); //   TypeError

The String constructor called as a function would be roughly equivalent to:

value+'';

The type conversion rules from Object-to-Primitive are detailed described on the specification, the [[DefaultValue]] internal operation.

In a brief, when converting from Object-to-String, the following steps are taken:

  1. If available, execute the toString method.
    • If the result is not a primitive, go to Step 2, else return the result
  2. If available, execute the valueOf method.
    • If the result is a primitive, return result, else Step 3.
  3. Throw TypeError.

Given the above rules, we can make an example of the semantics involved:

var o = {
  toString:function () { return "foo"; },
  valueOf: function () { return "bar"; }
};

String(o); // "foo"

// Make the toString method unavailable:
o.toString =  null;

String(o); // "bar"

// Now make the valueOf method also unavailable:
o.valueOf = null;

try { 
  String(o); 
} catch (e) {
  alert(e); // TypeError!
}

If you want to digg-in more in this mechanism I would recommend you to give a look to the ToPrimitive and the ToString internal operations.

Also I would recommend you this article:

CMS