Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console log with if, strange behaviour [duplicate]

I'm trying to leanr some javascript, however I can't quite answer why:

var a = 'xyz';
console.log('Example: ' + (a === 'xyz') ? 'A' : 'B');

Gives me back 'A' rather than Example: A. However when I put the whole if like that:

var a = 'xyz';
console.log('Example: ' + ((a === 'xyz') ? 'A' : 'B'));

It works flawlessly. Does that mean the first one puts the 'Example: ' string in a logical + with this if?

like image 496
Tomasz Avatar asked Feb 01 '26 21:02

Tomasz


2 Answers

It's not an if statement, it's a ternary operator.

But fundamentally, yes, what's happening is that first this part is evaluted:

(a === 'xyz')

...and becomes true or false. Then this is done (let's assume true):

'Example: ' + true

...resulting in:

'Example: true'

...then this is done:

'Example: true' ? 'A' : 'B'

...which gives us 'A' because the string isn't blank, and so it's truthy.

This is because + has a higher precedence than the ternary (? :).

like image 99
T.J. Crowder Avatar answered Feb 03 '26 11:02

T.J. Crowder


Exactly, as you can see + has higher precedence than ?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

So in your first expression string concatenation with the boolean value (a === 'xyz') gets executed first, the non empty string is then evaluated as a boolean true and 'A' is the final output.

In the second expression parenthesis force the ? operator to be executed before +.

like image 29
Andrea Casaccia Avatar answered Feb 03 '26 13:02

Andrea Casaccia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!