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 + ""
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?
toString()would be the way to go.toStringis 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, andvalue + ""is a bit of a hack. It also gives you the ability to override the defaulttoStringwith a custom implementation if you ever needed to I suppose, as a minor side benefit.+ ""is the fastest according to the jsperf, so... it does it ni some other way I guess.+ ""doesn't work reliably.. e.g."" + 308e65yields"3.08e+65"