Illogical Logicals
charles.russell — Mon, 07/19/2010 - 19:04
I have, and for the next several postings will be discussing JavaScript. Drupal makes extensive use of this language. Drupal even includes a tightly coupled JavaScript library of its own called drupal.js, this aside from the more general jQuery library. I am going someplace in this series so keep on coming. I think you will find the end result interesting. So let's get on with the next in this series.
JavaScript is a strange language in many ways but I thought I would focus on the particularities of JavaScript's logical operators || (or) and && (and). If you are coming from most other languages you are expecting these operators to return a boolean (true, false) value. In JavaScript this is not the case.
Let start with ||. If the first value is truthy then it is returned otherwise the second value is returned. This turns out to be extremely useful in a language that does not let you initialize variables in parameters. You can test to see if the parameter is set. If it is not then you can give the a value. This would look like:
a = a || “My Value”;
In simpler language, if there is a value in a keep it, otherwise set it to “My Value”.
The && has similar strange behavior. This returns the value of the second operand if the first value is truthy, otherwise the first is returned. This is used as a guard. Let us say that you want to insure a condition is true before assigning a value. For instance, it would make no sense to look for user name if the user is not logged in. && is very useful in a case like this. The following code illustrates assumes that there is a variable in scope called loggedIn.
getUser = function(){ result = loggedIn && userName; return(result); }
In this function if loggedIn is true, the function will return the user name, if not false would be returned. I have seen others use && to prevent null references. It is another good example of how this language is different from PHP, Java and most other languages.
Come back next week and see another bizarre but very useful aspect of this language.
