Search code examples
javascriptternary-operatorternary

Ternary operator not working properly in JS


I am running the following code and getting unexpected results:

var a = 1, b =2 ,c = 3;
console.log(5*a+ b>0?b:c);
Expected result was : 7 but getting 2.


Solution

  • Your code has the right concept, but wrong execution. The ternary is doing its job properly.

    At the moment, your code is executing like this:

    const a = 1
    const b = 2
    const c = 3
    
    // This will evaluate to true, since 5 * 1 + 2 = 7, and 7 is greater than 0
    if (5 * a + b > 0) { 
      // So return b
      console.log(b)
    } else {
      console.log(c)
    }

    You should use brackets to separate the ternary:

    const a = 1
    const b = 2
    const c = 3
    
    console.log(5 * a + (b > 0 ? b : c));