tags:

views:

155

answers:

4

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!

+7  A: 

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";)
Mark Byers
+4  A: 

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 +

Patonza
+1  A: 

In your first example, the third operand of the conditional operator is this:

('other_middle') + "-end"

You need to wrap the expression evaluated by the conditional operator, and BTW you don't need all those parentheses:

var url = "beginning-" + (someCondition ? 'middle' :'other_middle') + "-end";

Check this table of operator precedence.

CMS
A: 

Looks to me like a problem with operator precedence.

Javascript is interpreting the statement like:

IF ("beginning-" + (someCondition)) {
  'middle';
} else {
  'other middle' + "-end";
}

("beginning-" + (someCondition)) will be concatenated into a string (eg, "beginning-1") and since it's not null, it will be evaluated as boolean True, so the result will always be 'middle'

Chris Baxter