I always get excited when I discover a new feature or quirk of a language that allows me to write more concise code. Just when I start to think I have a decent understanding of a language a new doorway opens. In this case the revelation came through an often used operator in JavaScript. I will lovingly refer to it here as the “AND” operator primarily because that is the official name.
If you’re already a JavaScript expert you’ll likely not find anything new in this article and you’ll have to forgive my naivety. With that disclaimer out of the way, let’s look at some code.
if (true && "also true") { "it's true!"; }
If you throw that nugget in your console and press enter, not surprisingly you’ll get the output "it's true!" We could simply conclude that true && "also true" evaluates to, you guessed it, true and call it a day; however, we’d be wrong. Here’s what we’re missing.
true && "also true"; //=> "also true"
As you can see, it does not evaluate to the boolean primitive true like one might expect, but rather to the string "also true". In other words, the “AND” operator in JavaScript behaves much like a switch. It will give you the first expression when it is false, and the second expression otherwise. Hopefully the following examples clear up any confusion.
false && true; //=> false
0 && true; //=> 0
"" && true; //=> ""
null && true; //=> null
true && false; //=> false
true && null; //=> null
true && {"neat":"o"}; //=> {"neat": "o"}
true && "this could be anything"; //=> "this could be anything"
Hopefully you see that whenever the first expression is true or evaluates to true (meaning anything other than "", 0, -0, null, undefined or NaN) the second expression is returned. We can expand this definition a little to encompass chaining as well.
expression1 && expression2 && expression3 && expression4
In this case, the “AND” operator returns the first expression that evaluates to false or the last expression. “How is that useful,” you ask? For making toast of course!
alert(
haveALittleJelly()
&& haveALittleJam()
&& takeAPieceOfBread().putItInTheSlot(toaster)
&& toaster.pushDownTheLever()
&& assert(toaster.wiresGettingHot())
&& me.getToast(toaster)
&& "Yeah toast!"
|| "No toast.";
);
If we make it through all the steps we get a message saying “Yeah toast!”, otherwise we’ll get a message of “No toast.” If you’re confused by that “OR” operator (||) here’s the explanation: it works just the opposite of the “AND” operator. It will return the first expression that evaluates to true or the last expression. Here we take advantage of the operator precedence of JavaScript. The result of all those “AND” (&&) operators are calculated and sent as the first expression to the “OR” (||) operator. If we make it to all the way to “Yeah toast!”, we get “Yeah toast!” back, otherwise we get “No toast.”
Here’s a real world example taken from experimentation I am doing to integrate CouchDB into the ContractPal platform. For those familiar with CouchDB, this is from my validate_doc_update function. In the context the following code runs, newDoc is always defined, and oldDoc is defined if a version of the document already exists.
Before
var action;
if (newDoc._deleted) {
action = "delete";
} else if (oldDoc) {
action = "update";
} else {
action = "create";
}
After
var action = newDoc._deleted && "delete" || oldDoc && "update" || "create";
There are obvious pros and cons to both methods. I’d encourage you to do some of your own experimentation with the behavior of JavaScript’s logic operators and draw your own conclusions.
Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.