Search code examples
javascriptternary

Assignment from ternary operator ignores remaining expression


Doing this

const bool = true;
const a = 2 + true ? 3 : 0;
const b = 2 + false ? 3 : 0;

gives me a = 3 and b = 0. Why is the 2 + being ignored?


Solution

  • It has to do with Operator precedence https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

    As you can see in that table, addition (+) has a greater precedence than conditional (?). It makes the compiler read it like this:

    (2 + true) ? 3 : 0
    

    2 + true will evaluate first. As it is a truthy value, the result will be 3. If you want to change the default behaviour of the operator precedence, you will need to add the parenthesis:

    2 + (true ? 3 : 0)