Casting to string in JavaScript


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 + ""


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?

6/18/2012 1:37:38 PM

Accepted Answer

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.

5/23/2017 12:10:11 PM

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


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


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

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.


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


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


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