GTS Joe
GTS Joe

Reputation: 4152

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

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");
}

Upvotes: 3

Views: 549

Answers (4)

Bart
Bart

Reputation: 27205

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");

Upvotes: 0

user578895
user578895

Reputation:

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.

Upvotes: 0

Michael Malinovskij
Michael Malinovskij

Reputation: 1422

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);

Upvotes: 1

nzifnab
nzifnab

Reputation: 16092

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

Upvotes: 0

Related Questions