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");
}
+3
source to share
4 answers
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");
0
source to share
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
-1
source to share