Javascript Will Assign And Test A Variable In The Same Statement

Posted March 31, 2007 at 6:51 PM by Ben Nadel

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:

  • // 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!

  • <!-- 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.



Reader Comments

Mar 31, 2007 at 7:42 PM // reply »
21 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 »
105 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 »
10,640 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 »
168 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 »
10,640 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 »
10,640 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 ?


Aug 12, 2011 at 1:21 PM // reply »
1 Comments

I realize this is a 4 year old post, but please note that using this will create GLOBAL variables.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »