Advantages of setting variables inside a boolean evaluation expression

60 views Asked by At

On the MDN page for the wheel event, there is a code sample which includes the following at lines 30-31:

function( originalEvent ) {
  !originalEvent && ( originalEvent = window.event );

The second line seems to take a number of shortcuts that rely on the way JavaScript evaluates boolean expressions internally. If I understand correctly, its purpose is to set originalEvent to window.event if no argument is passed. Its action is the same as the following:

if (!originalEvent) {
  originalEvent = window.event;
}

or

orginalEvent = (originalEvent) ? orginalEvent : window.event;

What advantages are there in using the construction from the MDN site?

3

There are 3 answers

0
Morten Olsen On

To add more obscurity you could also use

function(originalEvent) {
  originalEvent = originalEvent || window.event;
}

There are no correct way of doing this, and they are all perfectly valid, I quite often use the one above, since i think it it more easily readable (though many will shake their fist at me for doing it). I also believe that you could get all method to go through most JSLint'ers with their default setting, so it really is a matter of style.

0
Blindy On

What advantages are there in using the construction from the MDN site?

Looking cool pretty much.

I was going to say terseness, but the following is just as short, and it's clear at a glance what's going on:

function(originalEvent) {
  if(!originalEvent) originalEvent = window.event;
}

Do note however that their sample doesn't rely on any "internal" order of operations or anything sinister. Operator short-circuiting (which is what this is called) is a very well defined and popular part of many languages, of which Javascript is just an example. You could write the same exact statement in C and it would work fine.

0
Josh Beam On

There is no perfect advantage of MDN's way over the ways you suggested. It's a matter of style.

All of the ways you mentioned do the exact same thing.

MDN's way is a little more "concise", but other people prefer if...else statements like the one you noted for readability purposes. Depends on the specific circumstances, but I think in most cases, choosing between one or the other is a matter of style, and not necessarily optimization.