Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
Ben Nadel at cf.Objective() 2014 (Bloomington, MN) with: Brett Davis
Ben Nadel at cf.Objective() 2014 (Bloomington, MN) with: Brett Davis@CFCoderMonkey )

Javascript Will Assign And Test A Variable In The Same Statement

By Ben Nadel on

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.

Looking For A New Job?

100% of job board revenue is donated to Kiva. Loans that change livesFind out more »

Reader Comments

Somewhat related:

Instead of:

var target = null;

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


var target = || event.srcElement;

You can do this with && too:

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

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.


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


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).

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."

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.


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?

@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

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

document.body.onload = function(){
var objHeader = document.getElementById("header");

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

but it dosen't work :-(

Any thoughs ?