Javascript – The ternary operator and if A, B, else C. Are there any important differences


There are a few ways to do this in javascript.

Foremost and most readable and flexible is probably:

if (a){
else {

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.

Best Solution


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


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.