I thought that using the unary + operator, concatenating with the empty string, and use of the not operator were implicit, while the use of the Number, String, and Boolean conversion functions, and the toString method, was explicit.
Also, as an ES6-specific warning, casting a symbol to string only works by passing it into the String conversion function or by calling its toString method; concatenating a string to a symbol throws a TypeError. Considering this together with the fact that property access on null or undefined also throws a TypeError, the safest way in general to cast to string is by passing into the String conversion function.
Boolean casting of symbols is fine either way, however (all symbols are cast to true), and although I would have liked numeric casting to turn symbols to NaN, instead it throws a TypeError both from the unary + operator and from passing into the Number conversion function. If you want to be fast and loose with the types, you could create a function like
function toNumber(val) {
if (typeof val === 'symbol' || Object.prototype.toString.call(val) === '[object Symbol]') {
return NaN;
}
return +val;
}
but maybe it's better to rely on the default behavior, and to figure that if code is passing in a symbol where a number is expected, something's seriously wrong.
I thought that using the unary
+operator, concatenating with the empty string, and use of the not operator were implicit, while the use of theNumber,String, andBooleanconversion functions, and thetoStringmethod, was explicit.Also, as an ES6-specific warning, casting a symbol to string only works by passing it into the
Stringconversion function or by calling itstoStringmethod; concatenating a string to a symbol throws aTypeError. Considering this together with the fact that property access onnullorundefinedalso throws aTypeError, the safest way in general to cast to string is by passing into theStringconversion function.Boolean casting of symbols is fine either way, however (all symbols are cast to
true), and although I would have liked numeric casting to turn symbols toNaN, instead it throws aTypeErrorboth from the unary+operator and from passing into theNumberconversion function. If you want to be fast and loose with the types, you could create a function likebut maybe it's better to rely on the default behavior, and to figure that if code is passing in a symbol where a number is expected, something's seriously wrong.