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
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 castSo 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
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