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
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)arguments[i] + ""
. This may or may not influence a decision on what to use. Some folks strictly adhere to JSLint.