Question

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?

Was it helpful?

Solution

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 (? :).

OTHER TIPS

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 don't set off (a === 'xyz') ? 'A' : 'B' with parentheses, the JS engine gives precedence to the + operator and interprets your truthy test as 'Example: ' + (a === 'xyz'), thus returning A.

It would return A even if the equality test were false, because a string concatenated with either true or false is still true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top