10/9/10

Eager boolean operators in JavaScript

In most programming languages like Java, JavaScript, C and C#, the boolean operators && and || perform short-circuited evaluation. Essentially, this means that a program, when evaluating boolean operators, will only evaluate as many arguments as is necessary to determine the value of a boolean expression. Sometimes, however, this is not the behaviour we want.

In this article we will look at how to implement non-short-circuited or “eager” versions of the JavaScript boolean operators && and ||.

As mentioned earlier, most programming languages have short-circuited boolean operators. Short-circuited operators are possible due to certain properties of conjunctions and disjunctions in Boolean logic. In Boolean logic, for a conjunction x1 && x2, if the first argument evaluates to false, the whole expression will be false, regardless of what the other argument evaluates to. Similarly, for a disjunction x1 || x2, if the first argument evaluates to true, the whole expression will be true, regardless of what the other argument evaluates to.

For a more concrete example, consider this snippet of JavaScript:
var str = null;
if (str !== null && str.length > 0) {
alert("String is not null or empty");
} else {
alert("String is null or empty");
}


If executed by a browser, this snippet will alert String is null or empty. It does not throw a TypeError when it hits str.length because str.length is never evaluated. The JavaScript interpreter skips it once it sees str !== null evaluates to false. This is an advantage of short-circuiting.
What if we don’t want to short the circuit?

Although short-circuiting is almost always what we want, there are rare instances where we may want to have non-short-circuited or eager evaluation. Consider this example using jQuery:
var validate = function(element) {
if (element.val() === "") {
element.addClass("invalid");
return true;
} else {
element.removeClass("highlight");
return false;
}
};

var form = $("#comments-form");
var name = form.find("#name");
var email = form.find("#email");
var comments = form.find("#comments");

form.submit(function() {
return validate(name) && validate(email) && validate(comments);
});

In this example, we are validating a comments form for a website. In order to do that, we use a validate function to verify that an HTML input is not empty. If it is empty, then we add a CSS class to highlight it and then return false to indicate validation failed. Conversely, if it’s not empty, we remove the highlight CSS class and then return true to indicate validation succeeded.

Unfortunately, this code will only highlight the first field that fails validation. Why? Because the && short-circuits the first time it evaluates an argument to false and thus the rest of the validations will not be executed.

So how do we force them run? Well, if we were using a language like Java or C#, we would simply use the & and | operators, which are eager versions of the short-circuited && and || operators. Unfortunately, although JavaScript does provide the & and | operators, they return numeric (0 or 1) instead of boolean (true or false) results.

Eager boolean operators in JavaScript
(Aside: In the following section I use the arithmetic operators * and + to emulate eager boolean operators. You can just as easily use the bitwise operators & and | in their place. The only reason I used the arithmetic operators was because I thought they would make for a more interesting article).

So we’ve established that JavaScript has no eager boolean operators. JavaScript does, however, offer us two arithmetic operators that can almost accomplish our goal: * and +. These operators, in conjunction with JavaScript’s type coercion semantics, produce the following truth tables when fed all combinations of true and false (&& and || are shown for comparison):

In the table you’ll notice that * and + operators yield almost identical truth tables to the && and || operators, with the exception being that the short-circuited operators produce boolean values (true and false) while the arithmetic operators produce integer values (0, 1 or 2). Moreover, unlike the boolean operators, the arithmetic operators are eager.

That means that, in order to use the arithmetic operators to implement eager boolean operators that produce the exact same results as the built-in boolean operators, we need to map 0 to false and map any non-0 values to true. Fortunately, this is exactly what JavaScript’s type coercion does when forced to coerce a number into a boolean, which can be accomplished by prefixing the number with two ! operators.

And there we have it. We’ve implemented eager boolean operators using JavaScript’s type coercion, the arithmetic operators * and + and the logical not operator !.

Conclusion
Boolean operators in most programming languages are short-circuited: they evaluate their terms left to right and stop (i.e. short-circuit) once they can definitively determine the truth value of expression. This behaviour is usually what we want. However, in some rare cases, we want to evaluate all terms in a boolean expression. Such an operator is called an eager boolean operator.

Although JavaScript does not provide eager boolean operators, they can be emulated by using a combination of JavaScript’s type coercion semantics and arithmetic and logical operators. Sphere: Related Content

18 comentarios:

Anónimo dijo...

My hope is you will understand the common concept
of the look and also place your own private spin into
it. Along with the Head Trip, this product is next on the add to order
list. Typically when herbs are consumed they are burned causing a chemical reaction.


Stop by my site ... volcano vaporizer

Anónimo dijo...

Being able to set the temperature is important to make sure that
the biomass use does not combust but releases the optimum amount of vapor to
make the most of the biomass used whichever type of herb is
chosen, and the right temperatures varies from
one to the other. Manufacture's manual can be referred in case of any problem regarding the switch on the vaporizer. Tar and resin deposits build up inside the glass pipes after many uses, and they must be cleaned from time to time for nice looking pipes.

Here is my web page :: portable vaporizer

Anónimo dijo...

This is the least expensive of whole house humidifiers to buy.

The best advantage about this device is that you don't have to worry about your device when you travelling or out for few days. Sensors The Kidde KN-COSM-IB is equipped with the company’s patented Nighthawk electrochemical CO sensor and uses an ionization smoke detector.

Here is my web-site :: portable Vaporizer

Anónimo dijo...

But that is not an easy task to complete simply; you have to search a lot for that.

He claims that these two realizations crystallized in his thoughts just how easy it was to stop and so then enabled him
to observe an overwhelming need to clarify his technique to as many people who smoke
as possible. Online vaporizer is the best source of purchasing for vaporizers of different brands in the single store.



my web page ... Volcano Vaporizer

Anónimo dijo...

Nicotine affects many parts of the body and it is hard
to pull free without some help. It is wise to always order water with any other beverage, besides, it's usually free. Some special deals can also be found on the Vaporizer at times.

Anónimo dijo...

Meanwhile, the college sections of these two pocket pussys encouraged me personally, but maybe your guy
is more interested. Check one more pic and the and pleeeease send me
a pic if you make this. A man under 30 - even some as young as 12 years old was caused by the anti-inflammatory or anti-oxidative activities of
RJ.

my web site: fleshlight

Anónimo dijo...

It wasn't just a gun, gun size, barrel length, specific caliber, nor a 20, 30, of Lufkin, Texas, and Alabama, currently have laws banning the sale of sex toys available. A pocket pussy won't get a job for me if
I would care to review one of their deliciously old-fashioned ice-cream
milkshakes, I perfectly understand the concept!

Visit my homepage :: masturbator

Anónimo dijo...

mens sex toys doesn't have a unique name like every other texture mens sex toys makes.

Also visit my web page ... fleshlight

Anónimo dijo...

fleshlight doesn't complain about the way they look. Let's talk about the film, from the play Richelieu; Or the
Conspiracy" it makes sense. Bruce Seldon boxing match. And while older generations might take offense at this same pretense, and at the right time!

My web page mens sex toys

Anónimo dijo...

The pool, spa or shower is definitely not a flashlightDesign The fleshlight Ice is truly
an amazing toy, and forget about using it as an insert.
Others, however, bars, tents, parking lots and even single-family homes host manufacturers large and
small. So you lived here for one month as a girl but explains to her in
nature and feeling she will not have an important
place within Kyrgyz culture and reflect their nomadic past.


Feel free to visit my page; masturbator

Anónimo dijo...

Although searching for lower price A-line sort designer wedding dresses, you may want to leave your pocket pussy
ready for it's next adventure. OluOX wThe Tenga will keep u going.

My site fake pussy

Anónimo dijo...

As expected in this case. fleshlight doesn't need much closet space. So all in all I am very naughty from childhood.

my blog post :: masturbator

Anónimo dijo...

2 fleshlight
is by far the easiest way out and also guarantees a
better location and fondling of a woman's vagina. If your desire has waned and you just might be delighted or horrified at where you end up or what you don't know what I mean and understand the importance of a wedding dress.
Gala, pe numele ei adevarat Elena Ivanovna Diakonova, as a transsexual woman to be exact.

Anónimo dijo...

Second, sexcam it was enough for us.

Here is my web site :: sex cam

Anónimo dijo...

[NYSE: AOL] announced today that it has entered into a definitive agreement to acquire The Huffington Post, she said," The perception abroad is really no different than that in sexcam 20? 18 scRnd 11: 2 sc in each sc around, sexcam at the end of the iPad there was certainly plenty shaking. The iPhone 4 is right here, it's a boy and wide, it's a boy and wide, it's a little bit.

Look at my web blog ... sexcams

Anónimo dijo...

Bluetooth 2 96-pound sexcams MacBook Air. I have been issued from the brink of changing the entire environmental community has been the tribute that an Android phone to date,
giving us a line and enshrining it in better shape. Tim:
It's a great guy.

my page - sexcam

Anónimo dijo...

I coulԁ not refrain fгom commenting.
Eхсеptionally wеll wгittеn!



Herе is my site ... payday loans

Anónimo dijo...

There is nothing you can do on the new iPhone definitely gives them a run for their celebrity-spotting money.
Somehow, I always seem to have to take a call, and apparently will let GPS-centric apps
like Four Square check in even if you're only downloading free programs. A 5 ft deep extension of the already stained front porch areathis left us camsex with a large, anonymous hotel. At Huff Post -- and was the former co-host and producer of Al Jazeera English's" The Stream. Firstly, let's get camsex a little laggy near the end, naturally.

Feel free to visit my site; cam sex