How to write shorthand if / else if / else?
Is there a shorthand for the if / else if / else statement? For example, I know there is one for the if / else statement:
var n = $("#example div").length;
$("body").css("background", (n < 2) ? "green" : "orange");
But how do I write the following in the shorthand syntax as above?
var n = $("#example div").length;
if (n < 2) {
$("body").css("background", "green");
}
else if (n > 2) {
$("body").css("background", "blue");
}
else {
$("body").css("background", "orange");
}
It exists, but it is highly recommended by the UN because it is quite difficult to read and maintain.
var n = $("#example div").length,
color;
color = (n < 2) ? 'green' :
(n > 2) ? 'blue' : 'orange';
$("body").css("background", color);
Tees are good if you are using line breaks:
$( 'body' ).css( 'background',
(n < 2) ? 'green'
: (n > 2) ? 'blue'
: 'orange'
);
Everyone has their own syntactic preferences, but I find it perfectly readable.
No cuts.
I would also like to point out that the?: Operator is not a shorthand. One expression, another statement.
If you want to make this code more concise, I would suggest getting rid of the curly braces:
if (n < 2) $("body").css("background", "green");
else if (n > 2) $("body").css("background", "blue");
else $("body").css("background", "orange");
You can use a triple for this, but I would recommend against (this is bad style). You can also go with a switch statement:
switch(true) {
case (n<2):
$("body").css("background", "green");
break;
case (n>2):
$("body").css("background", "blue");
break;
default:
$("body").css("background", "orange");
}
But it's no better than just sticking to if