Search code examples
javascriptjqueryif-statementshorthandshorthand-if

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

Solution

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