-
Notifications
You must be signed in to change notification settings - Fork 26.8k
Recommended ?: refactoring is worse #1677
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
Comments
A Similarly, if you're following the spirit of this guide, such a comparison would never have side effects nor throw, so in practice this is a non-issue. |
If your recommendation was specific to operations like const foo = cond1()
? val1()
: cond2() ? val2() : val3(); |
It does. However, if an operation is expensive, it should be stored in a separate variable to call it out, rather than being inlined in the middle of an innocuous-seeming operation. |
I disagree with this rationale. Even const operand = {toString(){throw 'x'}, valueOf(){throw 'y'}};
...
... operand < 3 ... Saying that "the code elsewhere should not have been changed this way" is no excuse for ignoring the possibility at the call site. Your recommendation text should at least warn about the potential non-equivalences of the recommended refactoring. |
This is a style guide, not a library or a specification; it doesn’t have to be concerned about things that simply don’t happen in practice (including defining custom valueOf/toString methods). If an operation throws, that’s fine. If it’s expensive, it should be stored in a variable and named so as to indicate that it’s necessary to cache it. The spirit of this guide requires explicitly coercing most everything prior to using it; if using > on non-number types, they should be converted to numbers first, making such comparisons always fast and safe. |
https://github.com/airbnb/javascript#comparison--nested-ternaries
The recommended refactoring of
into
is not equivalent. In the latter, the
value1 > value2
comparison is always evaluated, and one of'baz'
ornull
is also always evaluated. In this case, it is probably fine, but in general it has two problems:maybe1 > maybe2
.The text was updated successfully, but these errors were encountered: