Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

notes about type-casting #345

Open
lewisje opened this issue May 29, 2016 · 0 comments
Open

notes about type-casting #345

lewisje opened this issue May 29, 2016 · 0 comments

Comments

@lewisje
Copy link

lewisje commented May 29, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant