2

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?

0

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

6 Comments

Pretty complete answer +1.
very good answer. definitly true about the first line of code. when thr triple equal sign is used, it is looking to evaluate a bool value. Therefore, its looking for (a === true) or (a === false). in this case, a == should be used.
@Mic1780: The result is a boolean either way. == just adds type coercion. In the OP's example, there's no difference whatsoever between using == and === as both a and 'xyz' are strings. "Therefore, its looking for (a === true) or (a === false)" No, that comparison is never being done.
@Mic1780, no, === is the correct comparison. However, it doesn't really matter, because both String + true and String + false are true as long as String is not an empty string.
@DerekHenderson I see what you mean now after looking it up. The === evaluated the type and the value as the == does only the value. My mistake.
|
3

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 +.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.