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?
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 (? :).
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 +.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With