Quick Tip: What you May Not Know About JavaScript’s Logical AND Operator
videos

Quick Tip: What you May Not Know About JavaScript’s Logical AND Operator

Tutorial Details
  • Topic: JavaScript's && Operator
  • Format: 4 Minute Screencast
  • Difficulty: Beginner

In today’s video quick tip, we’ll be reviewing JavaScript’ logical AND operator. Those of you who are just beginning to get into JavaScript, or even a library like jQuery, might not realize that they can even be used as micro if statements!


Example 1: General Usage

// EXAMPLE 1
var a = 5,
	b = 10;

if ( (a === 5) && (b === 10) ) {
	alert('yay');
}

The AND operator’s use in the code above is what the huge majority of us are most familiar with. If a equals 5, and b equals 10, then do something awesome, like display an alert box that says, “Yay!”

The right side of the && operator will only run if the left side is equal to true. With that in mind, we can use this to our advantage!


Example 2: Checking if an Element Exists

In most of my AJAX-based applications, there will be a point where I must first determine whether an element with a particular id exists within the DOM. If it does not, I’ll create it. Otherwise, I’ll work with the element that already exists. Generally, we can use an if statement for this sort of task.

if ( !document.getElementById('contents') ) {
  // then call a function that inserts the element into the DOM.
}

Alternatively, we can use the && operator to accomplish this task.

!document.getElementById('contents') && createElem('div', 'contents', 'hello world');

Remember, that fake createElem function will, again, only run if the left side is equal to true. Think of it this way: is it true that we could not find an element with an id of contents on the page? If so, then move on to the right side. Now if it’s equal to false, the right side will never run.


Example 3: Loading jQuery Locally

When reviewing the HTML5 Boilerplate, I noticed that Paul uses a clever one-liner that potentially loads a local version of jQuery, if, for some reason, there was an error downloading the file from your CDN of choice.

!window.jQuery && document.write('<script src="localjQuery.js"><\/script>');

Is it true that jQuery does not exist? If so, move on to the right side, and insert a script element, which references jQuery locally. Nifty, eh?


Conclusion

Before you go crazy with this technique, be careful. It certainly makes for slightly less readable code, and that should be an important factor in your decision — especially when return to six month old projects!

Add Comment

Discussion 45 Comments

  1. Sam says:

    I usually use:

    if(typeof jQuery == “undefined”) document.write(“”);

    Is this not efficient enough?

  2. Haziq says:

    Awesome tip man! :)

  3. Abid Omar says:

    ooops, no download link :’( :’(

  4. The same technique is used a lot in PHP (even being a bad practice), when people code something like this: mysql_connect('...') or die('could not connect to the database');

    • Thomas says:

      The bad practice in this example is not the use of or, but the use of the die()

      A good alternative of your example would be something like mysql_connect(‘…’) or throw new Exception(‘could not connect to the database); (as long as your application catches the Exception and displays an error page)

  5. Mohamed Zahran says:

    I liked loading JQuery Locally :D and the code is very understandable, if jquery is not loaded, call the file within script tags ;) very awesome

  6. MISTULAH says:

    What I nice tutorial. Got new techniques. ^^.

  7. Tuto says:

    Oh. I am wander to the code of loading Jquery locally. I think I have to study more on HTML5 Boilerplate. Many thanks to writer Jeffrey Way

  8. david runion says:

    Do multiple things on the right side of the && conditional with the bitwise OR operator |:

    !!$(“#container”).size() && ($(“#container”).show() | window.containerReady = true | console.log(‘container ready’));

    I can’t remember where I got this from. Maybe John Resig but I can’t be sure.

  9. James says:

    Has any testing been done to decide which method is faster? I’m more likely to use this if it proves faster than if statements!

    Doing multiple things using the OR operator is nice too… again, has this been proven to run faster than an if statement?

    • Joao Lopes says:

      Well i’m guessing that this method is faster.
      The reason i’m saying this is because less tests are made.
      For example, when a compiler runs a code with an if on it, they have to test if it’s an if, and then test the condition.
      Within this example your only testing the condition.

      It’s like when you perform bitwise operations instead of logical ones.
      The bitwise operations are much faster because they work at the bit level and no interpretation is needed.

      Anyway, i’m guessing here ;)

    • Brian Egan says:

      Yo dude,

      You got me curious, and so I made up some tests with Jeff’s code. You can run the tests for yourself in various browsers:

      http://jsfiddle.net/qPA5h/ — Crazy JW Hacks
      http://jsfiddle.net/qPA5h/1/ — Plain ol’ if statements

      At least on my machine, it seemed like the regular if statement was just a * smidgeon* faster (maybe statistically insignificant).

      Therefore, it seems like it’s safe to use this method without performance impact at least. I like the brevity of it, but usually stick to “if” statements because the first time I saw that method used was on one of those “so you think you know JavaScript” quizes. In other words, it scares me =P

      Cheers,
      Brian

  10. Joao Lopes says:

    I’m shocked… I mean, i always knew that programming languages work like that (Check if true, if not jump out of it),

    but i never, ever knew how to take advantages of it. Thank you very much, i love this tips…
    Wonder if it works on other languages. It should since they are C based.
    I’ll try. Thanks again.
    :)

  11. Shane Parker says:

    Jeffrey, I noticed you’re using Espresso. I know you’re a big fan of Coda (I use Coda myself). Have you jumped ship from Coda to Espresso? I’ve read a lot of people online have done so. Any chance of getting an Espresso review?

    BTW, great tip! I use it myself quite a bit in both Javascript/jQuery and php.

  12. Codeforest says:

    Great tip for improving/optimising JavaScript even further.

    One question, the local jQuery part is checking if something went wrong with downloading jQuery from Google. But, I often saw that this problem is just stating Waiting for code.jquery.com in browser’s status bar. This solution would not help you if this happens.

    Is there any solution for this scenario?

    Thanks

    • Codeforest says:

      Ooops, I just tested this and am wrong. This code is working if you can not access jQuery from code.google.com.

      I can not reproduce the Waiting for code.jquery.com in browser’s status bar. Do you people had similar experience?

      Why does it happen?

      • Leigh Kaszick says:

        If i understand you correctly you could do a set interval and keep checking for the jquery object.. something like:

        (function jQueryCheck(){

        var intervalCount = 0;
        var t = setInterval(function(){
        if(window.jQuery){
        clearInterval(t);
        } else if(intervalCount >= 160) {
        clearInterval(t);
        //run jquery script tag inserter function here
        } else {
        window.status = ‘Waiting for code.jquery.com’;
        }
        }, 50);

        })();

        this will timeout after 8 seconds

  13. Sam says:

    Store your JS files locally – it saves the time and bother when things break.

    • Sam says:

      Also forgot to say but if you store your files locally then you can develop without Internet connection. If you’re mobile or loose connection you’ll be scrambling to find a previously downloaded or cached version.

      I can talk from experience, the connection here drops every hour. Keeps me focused on work though instead of being on here or reddit/digg :P

      • Eddie Monge says:

        The problem with using only local copies of things like jQuery is that you lose the speed benefit of the browser using cached versions of the script from CDNs. The reason jQuery advocates using CDNs is that if a user hits your site and the browser sees you are trying to load a script from a CDN that it has previously served, it will load it from cache, which is far, far faster then redownloading. You include the local copy in case the CDN has crashed and there isn’t a local cached version.

  14. Karamfil says:

    It can be even shorter :)

    Instead of negating the condition and waiting for true
    !document.getElementById(‘contents’) && createElem(‘div’, ‘contents’, ‘hello world’);

    you can wait for false
    document.getElementById(‘contents’) || createElem(‘div’, ‘contents’, ‘hello world’);

  15. Daniel says:

    Is is a tip for code-obfuscation 101?

    It’s a bad idea to write code like this, unless you’re in some kind of contest to write the shortest and hardest-to-read code. It takes two more characters to do it the obvious way (not much loss).

    if (!window.jQuery) document.write(‘<script src=”localjQuery.js”><\/script>’);

    If you take out the spaces around the condition parens it’s the same number of characters. Usually the most important thing is to write code that is easy to read and understand. The && operator is not normally used as a branching control structure, and therefore is more confusing when used in this context.

    As for the performance characteristics, have you measured them? Unless you have measured it you can’t say anything about the comparative speed (this point is addressed to comments, not the article itself). I’d guess that they are so near the same (in terms of speed) that it doesn’t matter at all, and it probably varies from one interpreter to the next.

    Finally, to those saying “you can execute multiple statements by using the OR operator”, BE VERY CAREFUL. The OR (||) operator has the same short-circuit characteristics as the AND (&&) operator. If you have code like this:

    thirsty() && (mix() || pour())

    If the ‘mix()’ call returns a value that logically evaluates to true then the ‘pour’ function will not be executed. Again, this quickly gets very confusing and can introduce subtle and hard-to-find bugs in your code. Simply changing the return value of the ‘mix’ function can affect whether pour() is called or not in this case. Better to abide by the law of least surprise, and do it the way you were taught in Programming 101:

    if (thirsty()) { mix(); pour(); }

    • david runion says:

      Just so we’re clear-you know, for posterity-this is how it’s done:
      thirsty() && (mix() | pour())

      | == bitwise OR operator
      || == logical OR operator

    • Eddie Monge says:

      I think your “obvious way” is in that code-obfuscation 101 class. It takes 2 more characters to do it the far more readable way:
      if (!window.jQuery) {document.write(‘’);}

      So many new developers, and even season devs, don’t get that the part after the parens is what should happen and don’t know that the next line after parens is what gets executed. I have seen far too much code that looks like:

      if (!window.jQuery)
      document.write(‘’);
      doStuff();
      doMoreStuff();

      that makes it hard to read and follow. Spend the extra 2 characters and wrap it.

  16. nykeri says:

    awesome tip performed an if without an if nice i wonder if other languages support that gonna try

  17. Ionatan says:

    You could make another post for the logical OR operator.
    You can also make a couple of usefull “tricks” with it like:
    var somevar = elem || fallbackelem

    somevar will be populated with elem if it evaluates to true or with fallbackelem if it evaluates to false.

  18. Cool. But it would be better if you’d use jsFiddle.net for putting up examples, people can play with.

  19. Eric says:

    Haha, I learned this last semester in my Programming Fundamentals class! It’s a very useful trick for languages that short-circuit.

  20. Jono says:

    I’m sorry, but I must agree with Daniel in this instance. Although Jeffrey has produced a well written article, I think that the idea itself is quite misguiding, particularly to budding Javascript programmers.

    What are the benefits of such shorthand statements? Yes you might save a couple of characters, but as the author himself admitted, he hasn’t performed any testing that might suggest any gains in runtime efficiency. Moreover, anyone who refers to this code at a later time is likely to be very confused. Why complicate things? Using traditional IF statements imposes structure within your code. It makes it much easier, and self documenting. Is this code clever? Perhaps. Is it good practice? Certainly not.

    • Jeffrey Way says:
      Author

      Hey guys — Just a note that I’m not advocating that you replace all of your if statements with this technique. Gosh, that would be awful! :) But, nonetheless, it’s a nice trick to know for quickies — if only for testing purposes.

      So, yeah, in 97.8% of the cases, just use an if statement.

      • Shane Parker says:

        Jeffrey, I think most of us were intelligent to assume you weren’t suggesting that we replace all our if statements with ‘short circuit ‘ methods. Of course Daniel is correct, but is completely over-analyzing this. There’s nothing wrong with using this trick here and there, especially for testing purposes.

      • Louis says:

        Even if you never use this technique, it’s always beneficial to understand the little subtleties of a programming language. This is a great tip, even if it isn’t practical, because it deepens understanding of the language, which is just as important, in my opinion.

      • skmvasu says:

        I thought I could save my self from all of the basic if..else construct. Why I can’t use this as a substitute? Does it carry any significant disadvantage in terms of performance?

  21. Mind. Blown. It’s so obvious but I never have realised you can do things that way. Cheers!

  22. Nice quick tip! :)
    +1 for the “Loading jQuery Locally” method.

  23. Om says:

    Few Words….

    The Return Value.

    in the following Code, for AND, the expression returns the Value, not just true.

    var a = ‘True’, b=’false1′, c=null;

    if ( ( a && b ) && c)
    // do something;

    you would think, it executes like following

    a && b, since both are true, therefore (a && b) is true, and then …
    (true && c) is false

    But Actually,

    (a && b) is equal to ‘false1′

    therefore,

    var returnValue = a && b;
    console.log(returnValue); // Firebug… Duhh….

    // outputs ‘false1′

    returnValue = ( a && b ) && c;
    console.log(returnValue);

    // outputs null;

    In other words, if all are true, the returned value will be the last true value,
    else, it will be first false value

  24. Nir says:

    Jeffrey, you are absolutely very good in writing and presenting development video in an efficient and an interesting way (I’ve seen the CodeIgniter series) but for this specific one – I’d say that it’s totally useless, and making the code unreadable.

    But it’s good example to explain how strict programming langauges are born – after having code full of phenomenons like this one.

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.