A VSCode Extension to Clarify Operator Precedence in JS
TL;DR: I wrote a VS Code extension which shows subscript parentheses in your JS code to help clarify operator precedence.
In fact, there was one dominant theme: misjudging operator precedence. Here are a few examples of the types of errors it uncovered:
// The + will be evaluated first.
// The resulting number can never be null
a + b ?? c
// The ! will be evaluated first.
// The resulting boolean can never be null
!foo == null
// Author assumed they were ||ing the two ternaries.
// They were not
conditionA ? a : null || conditonB ? b : null
Especially in complex nested expressions these are easy mistakes to make. I started thinking about how I could address this issue more fundamentally. How could we make it easier to understand operator precedence?
I realized that when I have a question about operator precedence, I add parentheses where I think they are implicitly present and then save my file. If I was right, Prettier will remove them since they are redundant. If I was wrong, the parentheses stay. Either way, my code now behaves as I expect. But this process requires that I first think to double check. What about the cases where I don't think to double check?
What if Implicit Parentheses Were Always Visible?
This line of thinking lead me to the idea of a VS Code editor plugin which adds the implicit parentheses as decorations. If watch this demo carefully, you can see that the plugin inserts small subscript parentheses around expressions clarifying precedence in cases where its non-obvious.
The plugin does not modify the actual file, but simply inserts them as decorations visible only in the editor.
Taking the examples above, they would be rendered like so:
₍a + b₎ ?? c
₍!foo₎ == null
conditionA ? a : ₍₍null || conditonB₎ ? b : null₎
My hope is that this minimally invasive plugin can be useful to help avoid bugs caused by precedence confusion.