I came across this recently and thought it would make a great SO question.
Suppose you are assigning a string to a local variable and you want to vary it by a simple condition. So you insert an inline if statement into the string:
var someCondition = true;
var url = "beginning-" + (someCondition)?('middle'):('other_middle') + "-end";
But this doesn't work as expected, the value of url will be "middle", not beginning-middle-end. This statement yields the expected result:
var url = "beginning-" + ((someCondition)?('middle'):('other_middle')) + "-end";
Best explanation of why this is wins the coveted answer flag!
It is of course to do with precedence.
var url = "beginning-" + (someCondition)?('middle'):('other_middle') + "-end";
is interpreted as:
var url = ("beginning-" + (someCondition)) ? ('middle') : (('other_middle') + "-end";)
That's because of precedence of operators.
The first example evaluates to:
if ("beginning-" + someCondition) {
url = 'middle';
} else {
url = 'other_middle' + "-end";
}
because the ? operator has precedence over +
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