Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Syntax: Inline Ifs in String Assignment Statements

Tags:

javascript

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!

like image 828
FriendOfFuture Avatar asked Jan 26 '26 21:01

FriendOfFuture


2 Answers

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";)
like image 147
Mark Byers Avatar answered Jan 29 '26 11:01

Mark Byers


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 +

like image 30
Patonza Avatar answered Jan 29 '26 11:01

Patonza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!