WHAT: this is a blog where i collect news about the usage of javascript a serious programming language on the client side and server side. WHY: because it seams to be the most ubiquitous language and has functions as first class objects, and closures and ....

Friday, July 18, 2008

Anonymus temporary variables: _,__

A post on ajaxian about this blog entry by Michal Till and a especially a comment by Andrea Giammarch delivered the idea for this blog entry:

When we write code we often do repeat in our code property lookups over and over

Example:
 
if( node && node.nextSibling && node.nextSibling.className=='x' ) return node.nextSibling.className;



We can use an extra variable to make the code much sorter, cleaner and even faster:
Simply declare some anonymous temporary variables at the beginning of your function
 
function(..) { var _,__;


Use them where ever you like:
 
if (_=node) if(_=_.nextSibling) if((_=_.className)=='x') return _;

_=a;a=b;b=_ // swap


Why '_' ? Well because it is almost not visible. It's a perfect name for a temporary placeholder, the name is just not relevant, the meaning is revealed by it's immediate context.

Look at the next loop over an array to perfrom an alert for each element with a text property:
 
for( var i=0, l=a.length; i<l;i++) if (a[i].text) alert(a[i].text);


We could use _ like this:

 
for( var i=0,l=a.length;_=a[i],i<l;i++) if(_=_.text) alert(_);


Or in a more extreme way:
 
for(__=a,___=0,____=__.length;_=__[___],___<____;___++) if( _=_.text) alert(_);


While this is a lot longer, when we remove the punctation it is just for a 0 length if text alert and thus emphasizes the important elements.

Whereas the version with 'i,l' was for var i 0 l a length i l i if a i text alert a i text and our brain has to filter it.

Of course as an experienced programmer you are used to the i,l,i++ etc. and you will recognize it as a typical loop pattern,

But with the _ vars we express it more explicit: don't care about that looping stuff. You can copy it and replace 'a' and it will work. We could get used to this pattern as well and it may be a help for beginners.

Or we use the new forEach:

 
a.forEach(function(_){ if( _=_.text) alert(_);});


Oh this creates a new function each time the loop is used, but that's a topic for the next blog entry ;-)

No comments: