Short comparison operators

This little tutorial/article will show you some simple ways of writing shorter code in JavaScript (Also usable in other languages). So lets say we have the following code to assign the value of field_a to varA, but when field_a is empty, a default value will be used.

var valA;

if (document.getElementById('field_a').value != '') {
	valA = document.getElementById('field_a').value;
}
else {
	valA = 'default value';
}

This code does the trick, and with it's 157 bytes it is nothing to worry about. But it also takes 8 lines, which doesn't improve readability. So lets move on to something called 'conditional operator'.

Conditional operator

The conditional operator exists in most modern programming languages, and exists of three parts: the condition, the value if the condition equals true and a value if the condition equals false. This is very efficient in most cases, because we can write the same code as before in 119 bytes, and more importantly, only one line:

var valA = document.getElementById('field_a').value != '' ? 
    document.getElementById('field_a').value : 'default value';

Or operator

The conditional operator works fine in most cases, but in our case the document.getElementById function is called twice, which is never a good idea. So in this case we can also use the or operator ( || ), which assigns the first true value (Anything other than 0) to our variable. So the above code can also be written in the following way:

var valA = document.getElementById('field_a').value || 'default value';

Which only uses 71 bytes and is much more readable than the first and second example.

Replies to Short comparison operators
3:20 - Sunday, 29th of May, 2011By Sugar

Great thinking! That really bkraes the mold!

14:34 - Sunday, 29th of May, 2011By yabczzqjxwd

O1qbTP <a href="http://refuzlwitbtu.com/">refuzlwitbtu</a>

19:22 - Sunday, 29th of May, 2011By pjfxryczfu

XN2jcQ , [url=http://akjiqwovunso.com/]akjiqwovunso[/url], [link=http://fpagtqcrigfm.com/]fpagtqcrigfm[/link], http://tosmerwqcoqg.com/

21:50 - Saturday, 12th of November, 2011By xblkurydhw

G4J4ja <a href="http://otpicnuvsnmz.com/">otpicnuvsnmz</a>, [url=http://kfftssodruxg.com/]kfftssodruxg[/url], [link=http://dgqmfxikdyaa.com/]dgqmfxikdyaa[/link], http://ziupxupkhulq.com/

Post reply

Name:
Email:
4 + 2**:
Message*:

* Required fields, ** Anti-spam question