Search code examples
javascriptoperators

Operator precedence of nullish coalescing and ternary


Can someone explain why result evaluates to 20 in this statement?

let result = 10 ?? true ? 20 : 30;

Given nullish coalescing evalutes the statement in a left-to-right manner and is of higher precedence than a ternary operator, why is it safe to not assume that result should be 10?

Note: if a grouping operator is added, then result is 10.

let result = 10 ?? (true ? 20 : 30);

Solution

  • As I understand it, a nullish coalescing operator (??) has a higher operator presedence than a conditional (ternary) operator, so it should execute first.

    (The docs say that ?? operator has an operator precedence score of 5, while ... ? ... : ... has a score of 4.)

    So

    let result = 10 ?? true ? 20 : 30;
    

    basically evaluates to

    let result = (10 ?? true) ? 20 : 30; // => 10 ? 20 : 30
    

    And given that 10 is a truthy value, it (10 ? 20 : 30) evaluates to 20

    Extra details

    You may notice that there is an "Associativity" column in the JavaScript table of operator presedence.

    And you may wonder if it plays a role in this case. But the answer to that seems to be that it doesn't. And that's stated in the following quote (from the docs):

    The difference in associativity comes into play when there are multiple operators of the same precedence.

    Source