Skip to main content
Ben Nadel at InVision In Real Life (IRL) 2019 (Phoenix, AZ) with: David Fraga
Ben Nadel at InVision In Real Life (IRL) 2019 (Phoenix, AZ) with: David Fraga

Javascript Will Assign And Test A Variable In The Same Statement

By
Published in Comments (11)

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.

Want to use code from this post? Check out the license.

Reader Comments

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!";

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

15,848 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).

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

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

15,848 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?

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

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 ?

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel