tags:

views:

59

answers:

4

Take the following javascript:

var x = (p) ? 1 : 0;

p can be any value. It there any situation the parenthesis can have effect?

If so: please provide examples.

A: 

I can't think of any reason you would need parenthesis there except for readability.

Tom Gullen
+1  A: 

In case p was divided into several boolean expressions with different operators, nested parenthesis can decide the order of how to expressions are computed. But I have the feeling you already know that, and it was not part of the question.

But no, parenthesis have no effect on p as a whole. And I don't know why would someone put them, for I don't think they improve readability.

SiN
A: 

No. It's sometimes done by analogy with:

if (p)

where the brackets are compulsory.

bobince
+1  A: 

This is a bit of a contrived example, but hey, why not?

var y = -2;
var x = (y+=2)?0:1?1:0;
alert(x); // will alert '1'

versus

var y = -2;
var x = y+=2?0:1?1:0;
alert(x); // will alert '-2'

Check out this Javascript precedence table: http://www.codehouse.com/javascript/precedence/. Anything below the ternary operator (e.g. "?:") is going to require parentheses if you use it in ternary operator's evaluated expression.

Faisal
Nice answer. But p was meant to be an expression, not a placeholder/pseudo-thingy.
doekman
Let me try to simplify my answer a little bit. Basically, if p is an expression that contains an operator with lower precedence than the ternary operator, you need to include parentheses around p or else the expression will be "split" on that operator. In this usage "p" can still be an expression (e.g. "y+=2") -- I'm not sure what you mean by a "placeholder/pseudo-thingy".Regardless, it seems like the chosen answer made things clearer than mine, though. :)
Faisal