2

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?

ghirlekar
  • 1,071
  • 1
  • 9
  • 10

4 Answers4

2

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)
Alberto Centelles
  • 1,215
  • 11
  • 24
1

try writing like this :

//if the desired Output is a=5 and b=2

const a = 2 + (true ? 3 : 0);
const b = 2 + (false ? 3 : 0;);
Rohit shah
  • 833
  • 4
  • 15
Chetan Mehta
  • 349
  • 3
  • 12
0

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

console.log(a);
console.log(b);

https://jsfiddle.net/74ds0der/

The code you have written gives a = 3, b = 3. Check out the jsfiddle link.

Shriharsha KL
  • 317
  • 1
  • 2
  • 11
0

Why is the 2 + being ignored?

It isn't. Given:

2 + true ? 3 : 0;

firstly 2 + true is evaluated. Since 2 is a number, the + is treated as addition and true is coerced to the number 1, the result is 3.

Then the ? causes 3 to be coerced to boolean true so of 3:0 the 3 is returned.

In the second expression:

  • false evaluates to 0
  • 2+0 evaluates to 2
  • 2? evaluates to true, so 3 is returned.

Given:

const b = 2 + false ? 3 : 0;

b is assigned the value 3.

RobG
  • 142,382
  • 31
  • 172
  • 209