-
Notifications
You must be signed in to change notification settings - Fork 557
Description
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.