Advertisement
JavaScript & AJAX

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

by

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!

Related Posts
  • Code
    JavaScript & AJAX
    Connect 4 With Socket.ioSocket io wide retina preview
    Today we'll see how we can use Node.js and Socket.io to create a multiplayer Connect 4 style game.Read More…
  • Code
    JavaScript & AJAX
    JavaScript Animation That Works (Part 2 of 4)Spriting icon large
    In the last post, we introduced the idea of spriting, an easy way to animate in JavaScript that works in all browsers. We also walked through how to set up the sprite as a background image for a div and then use a line of JavaScript to change the background position to make it appear as if the image has moved. Read More…
  • Code
    JavaScript & AJAX
    Ember.js TestingEmber components retina preview
    When I started playing around with Ember.js almost a year ago, the testability story left something to be desired. You could unit test an object without any trouble, but a unit test is only one way to get feedback when you're building a software product. In addition to unit tests, I wanted a way to verify the integration of multiple components. So like most people testing rich JavaScript applications, I reached for the mother of all testing tools, Selenium.Read More…
  • Code
    JavaScript & AJAX
    Introduction to HTML5 Desktop Apps With Node-WebkitHtml5 node webkit retina preview
    Using Node.js, we can create web applications easily. Now, thanks to the node-webkit we can also create desktop apps with it, using a unique combination of HTML5 and Node.Read More…
  • Code
    HTML & CSS
    Intro to Shadow DOMShadow dom retina preview
    Take any modern web page and you will notice that it invariably contains content stitched together from a variety of different sources; it may include the social sharing widgets from Twitter or Facebook or a Youtube video playing widget, it may serve a personalized advertisement from some ad-server or it may include some utility scripts or styles from a third party library hosted over CDN and so on. And if everything is HTML based (as is preferred these days) there is a high probability of collisions between the markup, scripts or styles served from various sources. Generally, namespaces are employed to prevent these collisions which solve the problem to some extent, but they don't offer Encapsulation.Read More…
  • Code
    JavaScript & AJAX
    jQuery Succinctly: jQuery PluginsJquery cover
    Use the $ Alias When Constructing a Plugin When writing a jQuery plugin, the same conflict prevention routine used with regular, old jQuery code should be implemented. With this in mind, all plugins should be contained inside a private scope where the $ alias can be used without fear of conflicts or surprising results.Read More…