Skip to content Skip to sidebar Skip to footer

Javascript Syntax: Inline Ifs In String Assignment Statements

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

Solution 1:

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";)

Solution 2:

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 +

Solution 3:

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.

Solution 4:

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'

Solution 5:

If the condition is also the value.

The short-hand var x = y || z; should also not be forgotten.

In this case I guess

var url = "beginning-" + (middle || 'middle_was_bad') + "-end";

Could be useful to some people.

Post a Comment for "Javascript Syntax: Inline Ifs In String Assignment Statements"