-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.

11
  • Why the react-native tag? Commented Nov 1, 2019 at 11:30
  • 1
    It's because it's returning b. You should use brackets to separate the ternary Commented Nov 1, 2019 at 11:32
  • 1
    Why do you expect 7? Commented Nov 1, 2019 at 11:32
  • 2
    Your condition is 5 * 1 + 2 > 0. If this is true (which it is), then b is returned (2). Works as coded. Commented Nov 1, 2019 at 11:34
  • 1
    Note that JavaScript doesn't care that you put the space where you did — the space doesn't do anything for operator precedence, only operators and parentheses do. Commented Nov 1, 2019 at 11:35

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.