Tags

, , , , , , , , , , ,

There are several methods by which you could define your IF – ELSE statement in Javascript and the usage depends on your application. The most common if-else statement looks like this,

if(<your_condition>){
    // Code to be executed on IF
}
else{
    // Code to be executed on ELSE
}

The above statement is the basic style of IF-ELSE statement, but what if we have a shorter style of writing if-else statements, that reduce the lines of code which could have an impact on the website or application performance?

If-else redefined

Here is an example, I have a DIV with ID #messageContainer which I need to populate via ReSTFull service myApp/service/messages. Now to populate this DIV I have to satisfy two conditions

  1. The ReSTfull service should return JSON with key ‘message’
  2. And if the message value in JSON is empty string, then in the DIV I have to show text ‘No messages’

By normal if-else statement the code would look like as follows,

$.get('myApp/service/messages', function(response) {
    if (response.message && response.message.length > 0) {
        $('div#messageContainer').text(response.message);
    }
    else {
        $('div#messageContainer').text('No messages');
    }
});

The lines count on the above code is 8, here is the shorthand version of the same code,

$.get('myApp/service/messages', function(response) {
    var message = ('undefined' !== typeof response.message 
        && response.message.length > 0) ? response.message : 'No messages';
    $('div#messageContainer').text(message);
});

By the shorthand version of it, the lines of code reduced to 4.

It’s quite simple to understand,

var x = (<your_conditions_goes_here>) ? what_to_be_done_if_condition_is_true : what_to_be_done_if_condition_fails

Start using shorthand if-else today, enjoy coding. 🙂

JS_logo

Cheers!