Advertisement
  1. Code
  2. JavaScript

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

Scroll to top
2 min read

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

1
2
// EXAMPLE 1
3
var a = 5,
4
	b = 10;
5
	
6
if ( (a === 5) && (b === 10) ) {
7
	alert('yay');
8
}

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.

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

4
}

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

1
2
!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.

1
2
!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!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.