JS/TS rule S6606 suggestion to replace || with ? is ambiguous

Hello thank you for providing such a helpful tool.

Rule S6606 (JS/TS) suggests to “Prefer using nullish coalescing operator (??) instead of a logical or (||), as it is a safer operator”.

The operators have different behavior.

false ?? 'text' returns false
false || 'text' returns 'text'

They are not interchangeable. Maybe some advice in the short info and the Rule Description would be helpful.

“This rule reports when disjunctions (||) and conditionals (?) can be safely replaced with coalescing (??).”

This is not the case.

Example TypeScript:
Because x can be a bool false the operators can not be safely replaced.

const x: null | undefined | boolean | string;

const y = x || '';

In this case a safe replacement is possible

const x: null | undefined | string;

const y = x || '';

In TypeScript the rule can be fitted to just take effect in cases where false is not possible, I don’t see that in JavaScript, maybe this should be a TS-only rule an be deactivated for JS.

Sincerely Paco

  • Operating system: Ubuntu 22.04
  • IDE name and flavor/env: VS Code
1 Like

Hello @paco,

thanks for reporting this. Indeed seems the rule is not properly checking the whole union. I’ve opened a ticket to fix this behavior.


1 Like

Hi, I think in typing, you mixed up the return values for this part of your post.
It should be the below instead.
It would be nice if you modify it so as to minimize confusion for others. Thanks.

false ?? 'text' returns false
false || 'text' returns 'text'

That’s correct, unfortunately I am not able to modify or edit the post.
Maybe because it is my first post or something.

Funny enough I can edit this reply.

Edited, thanks for the heads up @itunuloluwa.

Anyway we got the message :slight_smile:

Super! Thanks, everyone.

1 Like