Search code examples
javascriptformatbooleando-whileprettier

Why does prettier add an extra pair of parentheses here?


I was trying to format a block of code like this one:

let [a, b] = [64n, 2n];
do {
    console.log(a);
} while (a /= b);

I found that prettier adds an extra pair of parentheses around the while condition:

let [a, b] = [64n, 2n];
do {
    console.log(a);
} while ((a /= b));

I don't get why it does that. Seems like a bug, since both pieces of code give the same output. Is there any reason to prefer the second format?


Solution

  • The code while(<expression>) and while((<expression>)) will always be equivalent. However, it seems that Prettier is intentionally adding an extra wrapping parenthesis because the condition is an assignment.

    Documented in this GitHub issue. Here is what lydell said in December 2018

    Hi! This is actually intentional, since it is a common convention to wrap assignments in conditions in extra parens to show that you actually meant to use assignment (=) instead of comparision (===) (which is an easy mistake to make). For example, the no-cond-assign ESLint rule has an except-parens option for this case.