The only valid solution for almost all possible existing and future cases (input is number, null, undefined, Symbol, anything else) is String(x)
. Do not use 3 ways for simple operation, basing on value type assumptions, like "here I convert definitely number to string and here definitely boolean to string".
Explanation:
String(x)
handles nulls, undefined, Symbols, [anything] and calls .toString()
for objects.
'' + x
calls .valueOf()
on x (casting to number), throws on Symbols, can provide implementation dependent results.
x.toString()
throws on nulls and undefined.
Note: String(x)
will still fail on prototype-less objects like Object.create(null)
.
If you don't like strings like 'Hello, undefined' or want to support prototype-less objects, use the following type conversion function:
/**
* Safely casts any value to string. Null and undefined are converted to ''.
* @param {*} value
* @return {string}
*/
function string (str) {
return value == null ? '' : (typeof value === 'object' && !value.toString ? '[object]' : String(value));
}