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:
- Although some of these examples can also be accomplished with a conditional operator (
condition ? expr1 : expr2), the point of this article is to explore the potential of logical operators. - Javascript evaluates logical operators from left-to-right, which means it evaluates what's on the left of a logical operator before evaluating what's on the right. So in
a && b,ais evaluated beforeb. - In the examples below,
trueandfalsesimply represent anything (variable, function, etc) that evaluates totrueorfalserespectively. - Don't let shortcuts break code readability and maintainability. If your use of logical operators as a shortcut becomes to cryptic/complex, you may find yourself losing your 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.