halO

programming, hackery, rants, science and of course Opera

Subscribe to RSS feed

Posts tagged with "OR"

Operator tricks

, , , ...

Operators behave mostly the same in many different languages, but in some you can use some nice tricks to save some space. For instance, in ecmascript you can assign a variable value from a deep tree without the risk of the script aborting because the array value was undefined.

var foo = c && c[0] && c[0][1];

The code will assign foo the value of c[0][1] or unassigned. The equivalent of this code is

var foo;
if(c)
   if(c[0])
      if(c[0][1])
         foo = c[0][1];

Boolean operators are conditional if you use && or ||. Using the AND operator, the following statements will not be executed if the current is false. Using OR, the same is true if the current is true. Here is an example using conditional OR

var foo = (bar < 10) || 5; // assigns 5 or true

You can use conditional operators as a shorthand of if. The last evaluated statement is the returned value.

Assignation

The assignation operator, =, does in fact return a value and is not always true. The assignation operator returns the value that was assigned, so foo=10 returns 10. This is the basis of how this effective loop works:

for(var n=0,e;e=array[n];n++){}

As long as the array contains values that are not evaluated as false in a boolean context, such as 0, '', false and probably a few others, it works fine. The reason is that the loop continues as long as the middle statement is true, and the returned statement is array[n].