+
has higher precedence than ||
. What this means is that your code effectively means this:
var temp1 = "string1" + b;
var temp2 = c + "string2";
a = temp1 || temp2;
If you want the string to start with "string1"
, end with "string2"
, and have either b
or c
in the middle, then you can wrap the ||
section in parentheses to ensure it’s evaluated before the concatenation.
a = "string1" + (b || c) + "string2";
Example:
function log(msg) {
document.querySelector('pre').innerText += msg + '\n';
}
var a;
var b = false;
var c = "__C__";
a = "string1" + (b || c) + "string2";
log(a);
b = "__B__";
a = "string1" + (b || c) + "string2";
log(a);
<pre></pre>
4
solved Does || operator disable further concatenation? [closed]