JavaScript Syntax: Inline Ifs in String Assignments

I stumbled upon this recently and thought it would make a big SO question.

Suppose you assign a string to a local variable and want to change it with a simple condition. This way you insert the inline if line into the line:

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

But this does not work properly, the url value will be "in the middle" and not the start-middle. This statement gives the expected result:

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

The best explanation of why this wins the desired response flag!

+3
source share
5 answers

Of course, with priority.

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

interpreted as:

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

This is due to the priority of the operators.

First example:

if ("beginning-" + someCondition) {
  url = 'middle';
} else {
  url = 'other_middle' + "-end";
}

since the operator ?takes precedence over+

+4

:

('other_middle') + "-end"

, , BTW :

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

.

+1

, .

Javascript :

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

( "begin-" + (someCondition)) (, "-1" ), null, True, ""

0

.

var x = y || z;.

,

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

.

0

Source: https://habr.com/ru/post/1723290/


All Articles