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?
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?
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)
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;);
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.
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:
Given:
const b = 2 + false ? 3 : 0;
b is assigned the value 3.