views:

418

answers:

4

There are a few ways to do this in javascript.

Foremost and most readable and flexible is probably:

if (a){
    //b
}
else {
    //c
}

Something else that only* works with assigning and is less readable is:

var foo = 'c';
if (a){
    foo = 'b';
}

My main question, though, is about the last two methods I can think of:

var foo = a ? b : c;

var foo = a && b || c;

Are there any differences between these two expressions? Other than the readability which both lack.

*although you could assign foo to be a function, then execute it after the if statement.

+1  A: 

var foo = a ? b : c; -> foo is b when a is true else c. var foo = a && b || c; -> foo is true if a and b are true or c is true.

They do not evaluate to the same result as the latter is a boolean expression, not using a ternary operator.

Sascha
Annan
Sascha
+5  A: 

The ternary operator is certainly readable to me. Even moreso than the first example, since concise, logical code is always easier to understand than many lines of control code that do the same thing.

Marc Charbonneau
+3  A: 

I don't agree the first lacks readability as long as it is used correctly, IOW a, b and c are simple expressions themselves. This operator does get abused though in circumstances it ought not.

Similarly the second expression, using the result foo as anything other than a boolean would not be good. Using the boolean operators to return non-boolean values because thats the way they work is just confusing. However as a boolean expression its reasonable.

AnthonyWJones
+8  A: 

Suppose:

var a = false, b = '', c = 'bar';

Then:

var foo = a ? b : c; // foo == ''
var foo = a && b || c; // foo == 'bar'

The two are not equivalent; you should never use the boolean operators in place of the conditional operator. Like other answerers, I also am of the opinion that the conditional operator does not lack readability for simple expressions.

Miles
I'm guessing that's what Sascha was trying to point out but you did it much clearer. thanks :)
Annan