How to write in shorthand form if / else if / else?

527 Views Asked by At

Is there a shorthand for an if / else if / else statement? For example, I know there's one for an 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 like 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");
}
4

There are 4 best solutions below

2
Michael Malinovskij On BEST ANSWER

It is exist but it's highly UN recommended because it's pretty hard to read and maintain.

var n = $("#example div").length,
    color;

color = (n < 2) ? 'green' : 
        (n > 2) ? 'blue'  : 'orange';

$("body").css("background", color);
0
nzifnab On

You can use a ternary for this, but I would recommend against (it's 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 that's not really any better than just sticking with if

0
AudioBubble On

Ternaries are fine if you use line breaks:

$( 'body' ).css( 'background',
      (n < 2) ? 'green'
    : (n > 2) ? 'blue'
    :           'orange'
);

Everyone has their syntactical preferences, but I think that's perfectly readable.

0
Bart On

There's no shorthand.

I'd also like to point out that the ?: operator is not a shorthand. One's an expression, the other is a statement.

If you'd like to make this code more concise anyway, I'd suggest getting rid of the braces:

if (n < 2)      $("body").css("background", "green");
else if (n > 2) $("body").css("background", "blue");
else            $("body").css("background", "orange");