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

// 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!

Leave a Reply

Your email address will not be published. Required fields are marked *