64x64 icon dark hosting
Deploy New Relic now and get $135 off your Tuts+ subscription.

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


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

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.

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

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.

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?


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!