-1

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.
connexo
  • 53,704
  • 14
  • 91
  • 128
Avinash Kumar
  • 93
  • 1
  • 11

1 Answers1

5

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));
Kobe
  • 6,226
  • 1
  • 14
  • 35