There is no official ECMAScript or JavaScript language feature called “shorthand”. Developers are responsible for coining the phrase, probably after realizing that terms like Ternary Condition are a bit archaic. The Mozilla Core JavaScript Guide does an excellent job of highlighting many of these shorthand techniques throughout tutorials, but I thought it best to have a definitive list all in one place. If you have others you would like to add, please feel free to comment.
Boolean shorthand is probably most overlooked by beginners. It is a clean approach, even if you do not get a major decrease in file size. One thing to remember is that the exclamation point questions whether a value is false, not if the current value is the opposite of the initial variable value. This is a common mistake.
/*
-----------------------------------------------
Boolean Shorthand 1
-----------------------------------------------
If "a" is equal to true,
then do something.
Longhand:
var a;
if ( a == true ) {
// do something...
}
Shorthand:
*/
var a;
if ( a ) {
// do something...
}
/*
-----------------------------------------------
Boolean Shorthand 2
-----------------------------------------------
If "a" is NOT equal to true,
then do something.
Longhand:
var a;
if ( a != true ) {
// do something...
}
Shorthand:
*/
var a;
if ( !a ) {
// do something...
}
The following conditional shorthand statements are also known as Ternary Conditions. Paul Bakaus, the creator of the jQuery UI plugin, writes about advanced Ternary Conditions in his post aptly titled Advanced ternary conditions in JavaScript. I invite you to check out his post after digesting this simple example.
/*
-----------------------------------------------
Conditional Shorthand 1
-----------------------------------------------
If "a" is not defined, or is not equal to true,
then "a" is equal to "b".
Longhand:
var a, b;
if ( !a ) {
a = b;
}
Shorthand:
*/
var a, b;
a = a || b;
/*
-----------------------------------------------
Conditional Shorthand 2
-----------------------------------------------
If some condition is equal to true,
then "a" is equal to "b", or else
"a" is equal to "c".
Longhand:
var a, b, c;
if ( true ) {
a = b;
} else {
a = c;
}
Shorthand:
*/
var a, b, c;
a = ( true ) ? b : c;
At first glance, the next assignment operator shorthand (second) example does not seem all that useful. Why would you want to set multiple variables equal to a single value? As you advance in your JavaScript knowledge you will quickly find that this is useful when several variables need to be equal to an object, such as a function or an array. The jQuery JavaScript framework uses this technique when initializing the jQuery global namespace.
11/02/07 Update:
Assignment Operator Shorthand 2 now reads correctly. Instead of a = b = c = d it should have read d = c = b = a. Sorry for any confusion.
/*
-----------------------------------------------
Assignment Operator Shorthand 1
-----------------------------------------------
Longhand:
var a, b;
a = a + b;
Shorthand:
*/
var a, b;
a += b;
/*
-----------------------------------------------
Assignment Operator Shorthand 2
-----------------------------------------------
"d" is equal to "c", which is equal to "b",
which is equal to "a". Therefore, "d", "c",
and "b" are all equal to "a".
Longhand:
var a, b, c, d;
b = a;
c = b;
d = c;
Shorthand:
*/
var a, b, c, d;
d = c = b = a;
Object shorthand is the most commonly recognized shorthand technique, but many beginners miss out on this JavaScript goodness when learning online from tutorials dating back several years.
/*
-----------------------------------------------
Object Shorthand
-----------------------------------------------
Longhand:
var a = new Array();
var b = new Object();
var c = new String("myString");
Shorthand:
*/
var a = [];
var b = {};
var c = "myString"; // This is technically a primitive, and not an object.
// Execute a method on it, and it becomes an object.
/*
-----------------------------------------------
Object Array Shorthand
-----------------------------------------------
Longhand:
var a = new Array();
a[0] = "myString1";
a[1] = "myString2";
a[2] = "myString3";
Shorthand:
*/
var a = ["myString1", "myString2", "myString3"];
/*
-----------------------------------------------
Object Hash Shorthand
-----------------------------------------------
Longhand:
var a = new Object();
a["myStringKey1"] = "myStringValue1";
a["myStringKey2"] = "myStringValue2";
a["myStringKey3"] = "myStringValue3";
Shorthand:
*/
var a = {myStringKey1: "myStringValue1", myStringKey2: "myStringValue2", myStringKey3: "myStringValue3"};
Certainly one of the lesser known shorthand tricks is treating a string like an array. This technique mimics the behavior of the charAt() method, and is a straightforward substitute.
11/01/07 Update:
It appears that this does not work in IE. Sorry about that.
/*
-----------------------------------------------
charAt() Shorthand
-----------------------------------------------
Longhand:
"myString".charAt(0);
Shorthand:
*/
"myString"[0]; // Returns 'm'
The eval() function may not be as evil as some have been lead to believe, but there is still an alternative for when you are being scolded mercilessly by a senior developer. This bracket notation shorthand technique is much cleaner than an evaluation, and you will win the praise of colleagues who once scoffed at your amateur coding abilities.
/*
-----------------------------------------------
eval() / Bracket Notation Shorthand
-----------------------------------------------
NOTE:
Assumes a form with name attribute equal to "form_name",
and a form control with the value set equal to strFormControl.
Longhand:
var a, strFormControl;
a = eval( 'document.form_name.' + strFormControl + '.value' );
Shorthand:
*/
var a, strFormControl;
a = document.form_name[strFormControl].value;
Until you program your first public API or JavaScript framework, the following shorthand trick may not seem all that much shorter. However, experienced developers know that taking advantage of variable function arguments (parameters) can quickly cut down on file size. Instead of naming all your parameters, use the inherent arguments property available to every function. Any arguments passed to the function will be fed into this array-like property, and can be accessed by index. Note that you can access the length and values in arguments, but in order to use methods like push() or slice(), you have to create an array, and set it equal to arguments.
11/01/07 Update:
This example was edited slightly from the original version to avoid some confusion.
/*
-----------------------------------------------
Function Variable Arguments Shorthand
-----------------------------------------------
Longhand:
function myFunction( myString, myNumber, myObject, myArray, myBoolean ) {
// do something...
}
myFunction( "String", 1, [], {}, true );
*/
function myFunction() {
alert( arguments.length ); // Returns 5
for ( i = 0; i < arguments.length; i++ ) {
alert( typeof arguments[i] ); // Returns string, number, object, object, boolean
}
}
myFunction( "String", 1, [], {}, true );
Object literal shorthand can take a little getting used to, but seasoned developers usually prefer it over a series of nested functions and variables. You can argue which technique is shorter, but I enjoy using object literal notation as a clean substitute to functions as constructors.
/*
-----------------------------------------------
Object Literal Shorthand
-----------------------------------------------
Longhand:
function myFunction() {
this.myMethod = function() {}
}
var myObject = new myFunction();
Shorthand:
*/
var myObject = {
myMethod: function() {}
};
For the eval() example, it is important to note, that if you are after a particular form element, the full notation may be more useful/safe.
e.g.
var foo = document.forms['comments'].elements['description'].value;
Calling document.formname will work, but if your form name is generic-ish, and another element in the DOM with an id, or name (IE is not your friend) exists before the form, you’ll run into issues…
Same deal, on the element in the form.
If you create a field, with name=”length”, the short syntax will break there too.
I personally have a method like this to use the longhand, but save the typing…
function getFormElem(form, elem){
return document.forms[form].elements[elem];
}
This works if you pass an index, or a name…
var foo = getFormElem(’comments’, ‘email’);
var bar = getFormElem(0,’name’);
var baz = getFormElem(1,’length’);
//this is real important, if you have any form names, or fields with names like:
name, length, action, method, size, id, value, etc.
The function is handy too, because it returns a ref to the element, rather than the value, because the field might be an array, or a checkbox (that is unselected) ;-)
Cheers,
Steve
Hi Steve,
That’s a great tip — thanks for sending along that code!
Awesomeeee =]
very useful. thanks.
Very basic stuff but so many programmers do not use shorthand. Nice blog.
[...] Shorthand tips and tricks [...]
Thanks for this summary. I was not sure about the a = a || b meaning before I read your explaination. Is it sollely working in JS or in other languages ?
Thanks :)
[...] http://blog.reindel.com/2007/11/01/javascript-shorthand-tips-and-tricks/ [...]
About the Conditional shorthand (Ternary operators), it should be noted that you can stack them [ a ? b : c ? d : e; ],
and once you get used to it, it is just as readable.
I wrote an article on this ’bout a month ago on the Nigunim Developer’s blog
It focuses on the differences between Js and Php’s stacked ternaries.
re: Oncle Tom, the || bitwise works in many languages, although there are differences, especially when using more than one set.
Any tips on the || operator? I’ve always wondered if there’s a way of doing something like this:
if (a != (b || c || d || e))
instead of:
if ((a != b) && (a!= c) && (a!= d) && (a!= e)
I’ve tried it but it doesn’t work. Just thought you might have known if there is a correct way of doing this shorthand.
Thanks for the great article, by the way!
Hi Dave,
In this case your best bet is the JavaScript switch statement. This is as close as I’ve seen to doing what you need, although probably not considered shorthand.
Thanks for reading the blog!
This is really good for a java script programmer…I can say this is awesome.