tags:

views:

131

answers:

3

Any thoughts on function that will receive one argument and returns back by string representation of the argument in JavaScript?

If the given object implements .toString(), then the function should use it. Otherwise, the function can rely on what the JavaScript implementation offers.

So what I come up with is like this.

var convert = function (arg) {
  return (new String(arg)).valueOf();
}
+11  A: 
value = value+"";
Fabien Ménager
Damn, you beat me to it.
Pim Jager
Technically Jed's is slightly faster (e.g. less chars): arg+='';
scunliffe
+4  A: 

I'm not sure you even need a function, but this would be the shortest way:

function( arg ) {
    return arg + '';
}

Otherwise this is the shortest way:

arg += '';
Jed Schmidt
+2  A: 

All data types in JavaScript inherit a toString method:

('hello').toString();   // "hello"
(123).toString();       // "123"
([1,2,3]).toString();   // "1,2,3"
({a:1,b:2}).toString(); // "[object Object]"
(true).toString();      // "true"
J-P
but this doesn't work with.. (undefined).toString(); // error (null).toString(); // error
beatak