Search code examples
javascriptternary

Extra parenthesis required for ternary statement


Here is a simplified version of my code:

var cond = true;
var res1 = "400" + cond ? "%" : "px";
var res2 = "400" + (cond ? "%" : "px");

the result is as follows:

res1 = "%";
res2 = "400%";

Am I missing something? It seems like both statements should equal "400%" - why is the first one not picking up the first part of the string?


Solution

  • By JavaScript's operator precedence, conditional is lower than addition (well, concatenation, in this case). "400" + cond ? "%" : "px" is equivalent to ("400" + cond) ? "%" : "px".