DEV Community

Cover image for DeepCode's Top Findings #10: Confusing Use of '!'
cu_0xff 🇪🇺 for DeepCode.AI

Posted on • Originally published at Medium

DeepCode's Top Findings #10: Confusing Use of '!'

DeepCode offers an AI-based Static Program Analysis for Java, JavaScript and TypeScript, and Python. As you might know, DeepCode uses thousands of open source repos to train our engine. We asked the engine team to provide some stats on the findings. On the top suggestions from our engine, we want to introduce and give some background in this series of blog articles.

Language: JavaScript
Defect: Confusing Use of '!' (Category Defect)
Diagnose: Negation applied before instanceof. Check operator priorities - negation has higher priority than instanceof.

This instance is sponsored by npm cli - as usual, you can open the project in deepcode and follow along.

Have a look at the code below:

  if ((!strings instanceof Array))
    throw new TypeError('argument must be an Array[String]');

For me, this is a typical issue of syntax versus semantics. As from a syntactical perspective, this is fine code, it compiles, and kind of works. But seeing the double parenthesis, I guess the developer intended a different behaviour. Per definition, the condition will always be false (see MDN see Not Instance Of). It is pretty likely the developer made a mistake here.

DeepCode correctly provides an explanation of the problem. The negation operator (!) has a higher priority than instanceof and is there executed before. ! reviews the operand and if the value is truthy (see MDN Truthy ) negates that and delivers a false. Otherwise a true. Then comes instance of and obviously, both of them can never be an Array. The condition will always be false. The code should look like this:

  if (!(strings instanceof Array))
    throw new TypeError('argument must be an Array[String]');

DeepCode has seen this in 202 projects and also provides examples below. For me, these examples are extremely helpful as they nicely show the before / after. Especially when parenthesis and their ordering comes into play, I tend to get blind sometimes. So this helps enormously.

If you have another 5 minutes to spare, have a look at this table here MDN Operator precedence. Always good to refresh things a bit. My general advise: Instead of trusting on operator precedence wizardry - use correct parenthesis :-)

And if you are not sure if you have seen this in your own code, give it a check - deepcode.ai.

Top comments (1)

Collapse
 
mx profile image
Maxime Moreau

Hi, thanks for sharing, I didn't even know about this priority "issue" :)