-
Notifications
You must be signed in to change notification settings - Fork 23
Let’s forbid the mix of nullish-coalescing and comparison operators #48
Comments
There is lots of confusion in JS around && and || precedence; I’ve not seen this be a problem with equality comparisons. |
Could you link to the rationale behind this decision ? |
@ljharb This issue is not about the relative precedence between |
Same, we've yet to have a bug with logical operators and equality.
How is it not a logical operator? |
Nullish-coalescing is about providing a default value. Logical operators is about boolean logic. |
No, && and || in JS are not boolean operators, they are value selection operators, exactly as ?? is. If they were boolean operators they’d produce a boolean. |
I carefully didn’t said “operators on booleans”, but “boolean logic”. The two values of that logic correspond to the notions of “truthy” and “falsy”. But it doesn’t matter how we name it. The fact is, that |
Hi, I’m thinking more and more strongly that we should ban the mix of nullish coalescing operator (
|
How is that different than || or && when paired with == etc? |
The difference is in usage. |
|| is exceedingly often used for value selection - for defaults - so i don’t see it as any different. |
I think this example is flawed. PHP's
I disagree, I think it's pretty common to have |
Sure, that’s true - but i mean, i think the exceedingly rare pattern of |
Closing, since this proposal is at stage 4. |
Currently, mixing nullish coalescing and logical operators is forbidden:
a ?? b && c
— syntax errorIf we do want such a behaviour, I strongly think that it should be extended that to relational operators:
a ?? b == c
— syntax error.My reasoning is the following:
Per #26 (comment), there are the following popular choices of precedence levels for
??
:||
(C#, PHP, etc.) — it is the most reasonable choice if we want something very near to||
;Forbidding the mix of anything between those two levels of precedence has the two following concrete advantages:
That will avoid bugs if someone used to the precedence of Swift, resp. C#, incorrectly translate their knowledge to JavaScript. Since
a ?? b == c
have differing semantics in those two languages, forcing them to use parentheses in order to precise what they meant is the only way to disambiguate.That will leave us the opportunity to pick the useful (Swift/Kotlin) precedence level, in some future.
The text was updated successfully, but these errors were encountered: