CodeQL documentation

Unclear precedence of nested operators

ID: js/unclear-operator-precedence
Kind: problem
Severity: recommendation
Precision: very-high
   - maintainability
   - correctness
   - statistical
   - non-attributable
   - external/cwe/cwe-783
Query suites:
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

Nested expressions that rely on less well-known operator precedence rules can be hard to read and understand. They could even indicate a bug where the author of the code misunderstood the precedence rules.


Use parentheses or additional whitespace to clarify grouping.


Consider the following snippet of code:

if (x & y == 0) {
  // ...

It might look like this tests whether x and y have any bits in common, but in fact == binds more tightly than &, so the test is equivalent to x & (y == 0).

If this is the intended interpretation, parentheses should be used to clarify this. You could also consider adding extra whitespace around & or removing whitespace around == to make it visually apparent that it binds less tightly: x & y==0.

Probably the best approach in this case, though, would be to use the && operator instead to clarify the intended interpretation: x && y == 0.