Javascript Will Assign And Test A Variable In The Same Statement

Posted March 31, 2007 at 6:51 PM

Tags: Javascript / DHTML

I just came across this really awesome Javascript "shorthand". It's always great to feel like you know a language very well and then come across something totally new. Usually, when I write Javascript, I am used to assigning variable values and then checking to see if they exists before I use them:

 Launch code in new window » Download code as text file »

  • // Get the page header.
  • var objHeader = document.getElementById( "header" );
  •  
  • // Check to see if the header exists.
  • if (objHeader){
  •  
  • ... more code here ...
  •  
  • }

But, I just found out that through the beauty of variable assignment and short-circuit evaluation, the above two statements can actually be combined into a single IF statement. Sweet ass!

 Launch code in new window » Download code as text file »

  • <!-- HTLM header / span. -->
  • <div id="header"><span>Title Span</span></div>
  •  
  • <script type="text/javascript">
  •  
  • // Define the variables as null.
  • var objHeader = null;
  • var objHeaderSpan = null;
  •  
  •  
  • // In this IF statement, assign the variables and
  • // check to see if they result in valid objects.
  • if (
  • (objHeader = document.getElementById( "header" )) &&
  • (objHeaderSpan = objHeader.childNodes[ 0 ])
  • ){
  •  
  • // If we have gotten this far, then we have assigned
  • // DOM elements to both objHeader and objHeaderSpan
  • // and we KNOW that they exist. Aler inner HTML.
  • alert( objHeaderSpan.innerHTML );
  •  
  • }
  •  
  • </script>

Notice that within the IF statement above, I am assigning AND testing the existence of both the Header and the Span within it. And, through the amazing beauty of short circuit evaluation, we can be sure that if the Header does not exist and results in a NULL, then the IF statement will fail and the AND'd part (setting the header span) will never get executed.

This is waaay awesome.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Other Searches  |  Print Page



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Mar 31, 2007 at 7:42 PM // reply »
7 Comments

Yes, yes...it's very nice. I love tricks lke that.


Apr 1, 2007 at 12:55 AM // reply »
2 Comments

Somewhat related:

Instead of:

var target = null;

if(event.target) {
// DOM2 event property
target = event.target;
} else {
// IE proprietary event property
target = event.srcElement;
}

Do:

var target = event.target || event.srcElement;

You can do this with && too:

var message = ieStopsSucking && "Hallelujah!" || "Awwww, poo!";


Apr 1, 2007 at 3:50 AM // reply »
100 Comments

Most C-style languages have always allowed this but I generally advise against it as it confuses the heck out of people who don't realize you can do this. Especially when you do what you have done and use an implicit test of the resulting value (although of course with a boolean result you specifically do *not* want to test it against true/false explicitly!).

You'll find you can also do things like:

a = b = c = d = 0;

which sets all four variables to zero. Again, I'd say avoid this as it is cryptic and unclear.


Apr 1, 2007 at 9:35 AM // reply »
7,572 Comments

@Aaron,

Yeah, that is a cool one. I do like using that, especially for things that are different from browser to browser (like event models).

@Sean,

I have to say that I agree with that. I am always one who pushes for readability / maintainability over neat shorthands. However, creating a DOM node pointer and then checking to make sure it exists feels so standard at this point that it is something I might want to consider using.

This doesn't work in CF (I just checked).


Apr 1, 2007 at 11:01 AM // reply »
1 Comments

Lots of languages have this ability Some consider it confusing, Flex Builder actually issues a warning for it but compiles it anyway, but in some languages it's actually become a common idiom for certain situations, especially used in while loops. PHP comes to mind, where you often see this form used in processing recordsets returned from a database query:

while($rec = $stmt->fetchRow()) {
// process data...
}

Personally I don't find it so terribly confusing, but it does take a sharp eye and I prefer to use it sparingly. My rule of thumb for such things is, "imagine yourself having to look at this code two years from now."


Apr 7, 2007 at 6:14 PM // reply »
165 Comments

A couple other, similar, somewhat-cryptic time savers:

var a = b || c;

...sets a to b if b is truthy, otherwise it sets it to c.

var a = b && c;

...sets a to c if b is truthy, otherwise it sets it to b.


Apr 9, 2007 at 8:50 AM // reply »
7,572 Comments

@Steve,

The OR'ing I knew about, but I didn't realize that AND'ing would work that way. Very cool. If neither B or C are truthy, does A still get set to C or does it get null?


Apr 9, 2007 at 10:08 AM // reply »
2 Comments

@Ben: It seems (through some experimentation on the Firebug console) that if neither b or c are truthy, then a gets set to b.

var b = null;
var c = false;

var a = b && c // a = null

var b = true;
var c = false;

var a = b && c // a = false


Apr 9, 2007 at 10:18 AM // reply »
7,572 Comments

Awesome. Thanks for testing that. Good to know.


Feb 22, 2008 at 5:54 AM // reply »
2 Comments

I have tried to lay this different, to broke it into CSS

avascript:
document.body.onload = function(){
var objHeader = document.getElementById("header");
objHeader.outerHTML+='<script>window.onresize=document.getElementById("main").style.width="772px";</script>';
}

<!--[if IE]>
<script>
var objmain = document.getElementById("main");
function updatesize(){ var bodyw = window.document.body.offsetWidth; if(bodyw <= 790) objmain.style.width="772px"; else if(bodyw >= 1016) objmain.style.width="996px"; else objmain.style.width="100%"; }
updatesize(); window.onresize = updatesize;
</script>
<![endif]-->

but it dosen't work :-(

Any thoughs ?


Post Comment  |  Ask Ben

Recent Blog Comments
Mar 21, 2010 at 6:32 AM
ColdFusion CFPOP - My First Look
Apologies... The field name in the db for C. is "BounceCode" It stores the code / message which is returned in the email. Sorry for the confusion. ... read »
Mar 21, 2010 at 6:29 AM
ColdFusion CFPOP - My First Look
@Jose Galdamez, Hi Ben and Jose 1st of all.. big thanks to Jose for his Skype chat a few weeks back. Your time was much appreciated. I have come up with a rather unelegant solution to my problem a ... read »
Mar 21, 2010 at 3:42 AM
A New Wrist Pain
Chiropractic treatment is one of the best methods for treating numerous health problems naturally. After years of experience being a chiropractor, I have found that it is a powerful way to solve many ... read »
Mar 20, 2010 at 12:07 PM
Drawing On The iPhone Canvas With jQuery And ColdFusion
Simply awesome. Saved my day. ... read »
Mar 20, 2010 at 9:00 AM
Building A Fixed-Position Bottom Menu Bar (ala FaceBook)
I would like to say thx for an easy way to create a bottom bar. I do have a ?. Is it possible to center the bar if i want to resize it to ex 85%. Regards Offenbach ... read »
Mar 19, 2010 at 7:26 PM
MySQL 3/4 - com.mysql.jdbc.Driver And allowMultiQueries=true
Thank you very much for this post. Adding allowMultiQueries="true" in context.xml didn't help until I added it to url as allowMultiQueries=true Good idea is to use prepared statements and it will he ... read »
Jim
Mar 19, 2010 at 4:49 PM
Nobody Puts Baby In The Corner!
Wow. This is like suddenly finding a support group for your secret shame. I'm not alone! I always liked this movie, even though it is extremely cheesy. I just wish Jennifer Grey hadn't gotten the ... read »
Mar 19, 2010 at 4:47 PM
Application.cfc OnRequest() Method Affects OnError() Arguments
@Jason and @Ben, I've been doing some CF9 refactoring on our systems and noticed an odd occurrence with onError as well. Found a way to work around my problem, but what I saw was... Background: Our ... read »