-2
var notice = "She is" + present ? "" : "n't" + " here."; 

versus

var notice = "She is" + (present ? "" : "n't") + " here.";

After fiddling around, I notice that it's only the string before the

present ? "" : "n't" 
that's messing with it. But I have no explanation as to why, if I were to alert notice (and of course have present be truthy or falsey), that it comes up blank with the first example, and works fine with the second.
Test
  • 97
  • 4
  • 13
  • 6
    [*Operator precedence*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) might be a clue. – RobG Oct 27 '14 at 23:17
  • C'mon people, really, [nobody groks this](https://stackoverflow.com/questions/26596509/printing-out-bool-options-with-cout#comment41807427_26596509)? – The Paramagnetic Croissant Oct 27 '14 at 23:18
  • If that's the case. then wouldn't it be coming back as truth anyway, since Sheis+present, which let's say we set to 1, would be She is1, ohhhhh. so then I assume that comes up as nothing. but what about the + " here. ? – Test Oct 27 '14 at 23:21
  • Thank you. Sorry I'm new to this. – Test Oct 27 '14 at 23:26
  • Referring to RobG's link about precedence when you leave out the parenthesis you effectively get ("She is" + present) ? "" : ("n't" + " here."). No matter what present is this evaluates to if (true) then "" else "n't here". So no matter what you have for present you get "". And don't feel bad I had to scratch my head on this and I spend allot of time in JavaScript. – Blue Oct 27 '14 at 23:42

1 Answers1

0

When you write:

var notice = "She is" + present ? "" : "n't"  + " here.";

the addition operator + takes precedence so the parser treats it as:

var notice = ("She is" + present) ? "" : ("n't"  + " here.");

The expression "She is" + present returns true regardless of the value of present since it is converted to a string in the expression (and ToBoolean applied to any non–empty string returns true), so the full expression returns "", i.e. the true side of the conditional operation.

When the grouping operator is applied to the conditional part, it takes precedence over everything so the conditional is evaluated first:

var notice = "She is" + (present ? "" : "n't")  + " here.";
RobG
  • 142,382
  • 31
  • 172
  • 209