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?
They do behave differently when the
valueisnull.null.toString()throws an error – Cannot call method ‘toString’ of nullString(null)returns – “null”null + ""also returns – “null”Very similar behaviour happens if
valueisundefined(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.