github-actions[bot] 36c5c7a1d9
Create rule S6638: Binary expressions should not always return the same value (#1939)
You can preview this rule
[here](https://sonarsource.github.io/rspec/#/rspec/S6638/javascript)
(updated a few minutes after each push).

https://github.com/SonarSource/SonarJS/issues/3888

---------

Co-authored-by: alexander-kamushkin-sonarsource <alexander-kamushkin-sonarsource@users.noreply.github.com>
Co-authored-by: Alexander Kamushkin <alexander.kamushkin@sonarsource.com>
2023-06-05 16:14:23 +02:00

39 lines
1.2 KiB
Plaintext

Comparisons that always evaluate to true or to false, logical expressions that either always or never short-circuit and comparisons to a newly constructed object should not be used.
== Why is this an issue?
An expression that always produces the same result, regardless of the inputs, is unnecessary and likely indicates a programmer's error. This can come from
- confusing operator precedence
- expecting strict equality between different types
- expecting objects to be compared by value
- expecting empty objects to be `false` or `null`
- mistyping `>=` for `=>`
This can also happen when you put an assignment in a logical sub-expression. While not strictly a bug, this practice is confusing and should be avoided.
== How to fix it
Review the code around the issue to find out why the expression always produces the same result. Pay attention to the operator precedence, comparing objects of different types, and comparing objects by reference (not by value!).
=== Code examples
==== Noncompliant code example
[source,javascript,diff-id=1,diff-type=noncompliant]
----
!foo == null;
a + b ?? c;
x === [];
(foo=0) && bar;
----
==== Compliant solution
[source,javascript,diff-id=1,diff-type=compliant]
----
foo != null;
a + (b ?? c);
x.length === 0;
----