Thursday, March 30, 2006

Or-Assignment

In many languages a boolean expression eg "good OR bad OR ugly" will return a boolean object with one of two values, true or false. In the case of "good OR bad OR ugly" it will return true if any one of good, bad or ugly evaluates to true.

In JavaScript 

  1. A boolean OR expression will return that actual value that was evaluated to be true. These are executed in order and the first one to be true is returned, the rest are not evaluated.
  2. A reference that is null or undefined will be false, and a valid reference will be true.

This can make cross browser code rather compact, because very often you are checking for a value or reference that may be undefined in one browser, but defined in another.

so instead of

if (this.defaultView)

{

l_window = this.defaultView;

}

else

if (this.parentWindow)

{

l_window = this.parentWindow;

}

else

{

l_window = null;

}

you can write simply, which will assign a value to l_window of either this.defaultView or this.parentWindow, depending on which is non null.

l_window = this.defaultView||this.parentWindow; 

These are executed in order and the first one to be true is returned so you can mix this up and get some rather complicated behaviors by ordering them on order of desirability and you can optomise these by placing the most common first.

Here are some testcases that probe the behavior of 'Or-Assignment'.

Multiple Returns

Suppose you want to return more than one object from a function. In most structured languages this is a matter of have defined a structure/class to return your multiple values in.

function multiple_out(a,b) { return {x:a , y:b}; } var l_result = multiple_out(1,2);

In JavaScript you can simply roll an object dynamically and add some named objects and return them.

I just went through some JavaScript code and managed to get a speed increase with minimal change to the code using this method.

See this testcase for some examples.

 

Thursday, March 30, 2006 1:54:50 PM (AUS Eastern Standard Time, UTC+10:00)  #    Comments [1]