
Co-authored-by: Marco Borgeaud <89914223+marco-antognini-sonarsource@users.noreply.github.com>
59 lines
2.5 KiB
Plaintext
59 lines
2.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Operator precedence determines the order in which different operators are evaluated when an expression contains multiple ones. It helps determine how the expression is parsed and executed. JavaScript follows a specific set of rules to determine operator precedence.
|
|
|
|
Not being aware of JavaScript's operator precedence rules can lead to unexpected and potentially incorrect results when evaluating expressions. This is common when misapplying the logical negation operator (``++!++``). For instance, consider the difference between ``++!key in dict++`` and ``++!(key in dict)++``. The first looks for a boolean value (``++!key++``) in ``++dict++``, and the other looks for a string and inverts the result. The same applies for ``++!obj instanceof SomeClass++``.
|
|
|
|
This rule raises an issue when the left operand of an ``++in++`` or ``++instanceof++`` operator is negated with ``++!++``.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
if (!"prop" in myObj) { // Noncompliant: checks whether !"prop", that is, false is in myObj
|
|
doTheThing(); // this block is never executed
|
|
}
|
|
|
|
if (!foo instanceof MyClass) { // Noncompliant: "!foo" returns a boolean, which is not an instance of anything
|
|
doTheOtherThing(); // this block is never executed either
|
|
}
|
|
----
|
|
|
|
You should use parentheses to force the order of evaluation of expressions mixing negation and ``++in++`` or ``++instanceof++`` operators.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
if (!("prop" in myObj)) {
|
|
doTheThing();
|
|
}
|
|
|
|
if (!(foo instanceof MyClass)) {
|
|
doTheOtherThing();
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence[Operator precedence]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#table[Operator precedence table]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT[Logical NOT (``++!++``)]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof[``++instanceof++``]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in[``++in++`` operator]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Add parentheses to disambiguate this expression.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
minus operator
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|