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 !
.
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.
if (!("prop" in myObj)) {
doTheThing();
}
if (!(foo instanceof MyClass)) {
doTheOtherThing();
}