Brian Cray ··· Home > Blog > Javascript > Diving deep into javascript logical operators

Diving deep into javascript logical operators

I have lots of fun finding shortcuts in javascript, and logical operators can make for some interesting ways to act on a condition. In this article we'll look at the logical operators && (read: AND) and || (read: OR).

A few things to keep in mind:

If else, without the if else

// traditional
if (true) {
    do_this();
}
// alternative method with &&
true && do_this();

// traditional
if (false) {
    do_this();
}
// alternative method with ||
false || dont_do_this();

// do multiple things via anonymous wrapper
true && (function () {
    do_this();
    and_this();
    ...
})();

// real example - test if DOM object exists before acting on it
jQuery('#alert').length && (function () {
    var el = jQuery('#alert');
    el.show();
    window.setTimeout(function () {
        el.hide();
    }, 5000);
})();

Conditional assignment

// setting defaults with ||
var my_setting = optional_setting || default;

// real example - if input#email is blank, defaults to none@none.com with ||
var email = jQuery('#email').val() || 'none@none.com';

// setting value only if something else is true with &&
var my_setting = test_me && setting;

// real example - setting email if valid with &&
var email = jQuery('#email').val().search('/[\d\w\.\-\_]+@[\d\w\.]/') > -1 && jQuery('#email').val();

// complex usage (mimic conditional operators)
var my_setting = (test_me && optional_setting) || default;

// real example - setting email if valid, with default
var email = (jQuery('#email').val().search('/[\d\w\.\-\_]+@[\d\w\.]/') > -1 && jQuery('#email').val()) || 'none@none.com;

Method calls on conditional variables

// use parenthesis to act on a condition
(check_if_true && use_this_if_true).method();
(use_if_true || else_use_this).method();

// real example - Add form field error above itself if it's not wrapped in a <form> with ||
(jQuery(this).closest('form') || jQuery(this)).insertBefore('<p>Error!</p>');

// real example - Add form field error only if it's a <form> with &&
// note: this will error if not in a form and not in a try...catch
(jQuery(this).closest('form') && jQuery(this)).insertBefore('<p>Error!</p>');

Conclusion

Javascript's conditional operators allow us to do some neat tricks. We looked at how to use them to bypass if...else, make variable assignments based on conditions, and call methods depending on conditions. But with all shortcuts, use caution. Knowing how javascript works will help you use conditional operators to their full potential while keeping you safe from unexpected results.