了解具有连接字符串的三元运算符

I am using JavaScript examples, however, it is not meant to be a JavaScript only question as the results are the same for PHP and I expect many languages. I've "dealt" with my lack of understanding by using a multitude of parentheses, however, it is time to deal with it.

Given the script below (and also at https://jsfiddle.net/5z4paegb/)..

function testTernary(isjane) {
  var str = 'hello ' + isjane ? 'Jane' : 'Mary';
  console.log(isjane, str);
}
testTernary(true);
testTernary(false);
testTernary(1);
testTernary(0);
testTernary(null);

I would have expected:

true hello Jane
false hello Mary
1 hello Jane
0 hello Mary
null hello Mary

But I get:

true Jane
false Jane
1 Jane
0 Jane
null Jane

According to JavaScript's precedence table,

'hello ' + isjane ? 'Jane' : 'Mary';

is equivalent to:

('hello ' + isjane) ? 'Jane' : 'Mary';

This is because the + operator has a higher precedence than the ?: ternary operator. (The ?: operator is actually quite low on JavaScript's precedence table, higher only than assignment operations, yield, ..., and ,.)

You can get your desired effect with:

'hello ' + (isjane ? 'Jane' : 'Mary');

In general, when dealing with the ternary operator, it's best to put parenthesis around the ternary operator and its operands so that it's explicitly clear what is part of the conditional operation.

This is also the case in PHP's operator precedence table as well.

Your ternary operator will evaluate to true because you are evaluating a concatenated string,

you could do this instead:

isJane = isJane ? "Jane" : "Mary";
var str = "hello" + isJane;

or:

var str = "hello" + (isJane ? "Jane" : "Mary");