-1
var str1 = "string1" + (false)?"string2":"string3";   // output: string2
var str2 = "string1" + (true)?"string2":"string3";    // output: string2

Why do these expressions evaluate to "string2" regardless of true/false in the condition?

What happens to "string1" and "string3" ? How exactly are these expressions being evaluated?

Shishir
  • 1,988
  • 17
  • 21

1 Answers1

8

Because ? has less precedence than +

"string1" + (false)?"string2":"string3"

is equivalent to saying:

("string1" + false) ? "string2" : "string3"

"string1" + false evaluates to the string value "string1false" which is truthy (Thanks @Vache)


To get it to work the way you want, add braces around the ternary expression.

"string1" + (false  ? "string2" : "string3")
techfoobar
  • 61,046
  • 13
  • 104
  • 127