243

I found three ways to cast a variable to String in JavaScript.
I searched for those three options in the jQuery source code, and they are all in use.
I would like to know if there are any differences between them:

value.toString()
String(value)
value + ""

DEMO

They all produce the same output, but does one of them better than the others?
I would say the + "" has an advantage that it saves some characters, but that's not that big advantage, anything else?

9
  • 1
    Seems to me that if all things are equal, the standard toString() would be the way to go. Commented Jun 18, 2012 at 12:50
  • 7
    In my opinion toString is semantically the clearest way to self document the fact that you are trying to get a string equivalent of an object. String(...) is a little obtuse, and value + "" is a bit of a hack. It also gives you the ability to override the default toString with a custom implementation if you ever needed to I suppose, as a minor side benefit. Commented Jun 18, 2012 at 12:54
  • 2
    @Adriano. But + "" is the fastest according to the jsperf, so... it does it ni some other way I guess. Commented Jun 18, 2012 at 13:05
  • 2
    @gdoron with toString() there is an extra check for null before the method call. According to 11.6.1 the "+" operator should call ToString() for both operands if one of them is a string. Results are pretty different for each browser (different optimizations paths?) Commented Jun 18, 2012 at 13:18
  • 2
    + "" doesn't work reliably.. e.g. "" + 308e65 yields "3.08e+65" Commented Nov 14, 2013 at 17:10

9 Answers 9

292

They do behave differently when the value is null.

  • null.toString() throws an error - Cannot call method 'toString' of null
  • String(null) returns - "null"
  • null + "" also returns - "null"

Very similar behaviour happens if value is undefined (see jbabey's answer).

Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.

Sign up to request clarification or add additional context in comments.

7 Comments

This is actually an interesting difference. So you should refrain from using toString() when you haven't checked for null yet.
@SammyS. don't know if printing null or undefined to the screen is a more desirable behaviour then a javascript error...
@JustusRomijn: True indeed. In the meantime, I started to use the Option type to handle such errors.
you can check any of these casted variables with typeof to check for string. typeof (null+'') == 'string'
There is another case when they behave differently. v + '' returns incorrect result if v has both toString() and valueOf() methods. Concatenation will ignore toString() and will use valueOf(). Example of a class for which concatenation fails: github.com/processing-js/processing-js/blob/…
|
39

There are differences, but they are probably not relevant to your question. For example, the toString prototype does not exist on undefined variables, but you can cast undefined to a string using the other two methods:

​var foo;

​var myString1 = String(foo); // "undefined" as a string

var myString2 = foo + ''; // "undefined" as a string

var myString3 = foo.toString(); // throws an exception

http://jsfiddle.net/f8YwA/

1 Comment

If a variable is not at all defined, you will still get an error for String(). Example: String(test); throws Uncaught ReferenceError: test is not defined, while var test; String(test); will result in "undefined".
21

They behave the same but toString also provides a way to convert a number binary, octal, or hexadecimal strings:

Example:

var a = (50274).toString(16)  // "c462"
var b = (76).toString(8)      // "114"
var c = (7623).toString(36)   // "5vr"
var d = (100).toString(2)     // "1100100"

Comments

16

In addition to all the above, one should note that, for a defined value v:

  • String(v) calls v.toString()
  • '' + v calls v.valueOf() prior to any other type cast

So we could do something like:

var mixin = {
  valueOf:  function () { return false },
  toString: function () { return 'true' }
};
mixin === false;  // false
mixin == false;    // true
'' + mixin;       // "false"
String(mixin)     // "true"

Tested in FF 34.0 and Node 0.10

Comments

10

According to this JSPerf test, they differ in speed. But unless you're going to use them in huge amounts, any of them should perform fine.

For completeness: As asawyer already mentioned, you can also use the .toString() method.

4 Comments

That jsperf has the same test twice, I edited it And the new String() returns an object not a String
new String() returns an object yes. String(), however, returns a string, which is the one in the question.
This is not entirely true. As you can see from the results, concatenating an empty string and an object does not yield the same result as concatenating an object and an empty string. Furthermore, new String(blarg) gives you a String object you can call toString() on. In my Chrome debugger, they effectively result the same kind of object except said difference.
@SammyS. Could you please add example performance results to your answer? The jsperf link currently is down and certainly will be again in the next 5+ years.
9

if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '') is faster.

see http://jsperf.com/cast-to-string/8

note - there are significant differences across browsers at this time.

1 Comment

"[T]here are significant differences across browsers at this time" should be good enough reason to disregard this. Nothing's changed much in 10 years, apart from the limitation of browser choice.
6

Real world example: I've got a log function that can be called with an arbitrary number of parameters: log("foo is {} and bar is {}", param1, param2). If a DEBUG flag is set to true, the brackets get replaced by the given parameters and the string is passed to console.log(msg). Parameters can and will be Strings, Numbers and whatever may be returned by JSON / AJAX calls, maybe even null.

  • arguments[i].toString() is not an option, because of possible null values (see Connell Watkins answer)
  • JSLint will complain about arguments[i] + "". This may or may not influence a decision on what to use. Some folks strictly adhere to JSLint.
  • In some browsers, concatenating empty strings is a little faster than using string function or string constructor (see JSPerf test in Sammys S. answer). In Opera 12 and Firefox 19, concatenating empty strings is rediculously faster (95% in Firefox 19) - or at least JSPerf says so.

1 Comment

+1 for a real world example. Here's another gotcha with jQuery: $('#field-id').val() returns undefined if there is no such field. Casting this to a string (by whichever method) before testing it results in a failure: either an exception that's unhandled, or the string "UNDEFINED" which is indistinguishable from the user input "UNDEFINED". Of course, it would be better and much more expected if JS converts it to an empty string, but it's browser-specific. Make sure you know what you're dealing with when using any of the above. Don't break your site for the sake of a few microseconds.
0

On this page you can test the performance of each method yourself :)

http://jsperf.com/cast-to-string/2

here, on all machines and browsers, ' "" + str ' is the fastest one, (String)str is the slowest

1 Comment

Function over form, please, or, in this case, reliability over performance. "" + str results in the string "UNDEFINED" when str is undefined, which is probably not what you want.
-1

Use Backticks

so:

`${varibale}`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.