Shorthand Javascript Techniques


(This is for coders familiar with the JavaScript language. Information on more basic JavaScript usage can be found at sites like w3schools.com.)

Summary

Keeping code standardized can be made easier through JavaScript shorthand. Here we will be looking at several techniques that will make code more readable, flexible and overall easier to matain.

Declarations
Conditions
Mathematic Operations
Anonymous Functions

Declarations

Variables

Instead of declaring each variable individually, they can be placed on the same line with a comma separating them.

var foo1, foo2, foo3, foo4;

Arrays:

var foo_arr = ['bar1',  'bar2',  'bar3', ' bar4'];
window.alert(foo_arr[0]); //bar1

Objects:

var foo_obj = {name:  'bar', some_prop: 'test'};
window.alert(foo_obj.name); //bar

Conditions

condition? true_logic :  false_logic;

Shorthand conditional statements can be coupled with an assignment, allowing  a single line of code to be used for simple conditional logic.

var foo = bar? 1 : 0;

Assigning a default value when encountering an empty variable (null, undefined, 0, false, empty string) can also be shortened from this

if(foo) {
    bar = foo;
} else {
    bar = 'Default Value';
}

to this

bar = foo || 'Default Value';

Mathematic Operations

Handling math operations can be shorted by using the following syntax:

foo = 5;

foo ++; // Increase by one

foo --; //Decrease by one

foo -= 2; //Decrease by two

foo += 2; //Increase by two

foo *= 3; //Multiply by three

foo /= 2; //Divide by two

Anonymous Functions

Assigning a function to a variable:

var my_func = function() { alert('Hello World') }
my_func;

Inline anonymous functions:

var foo = {
    name: 'bar',
    fnc:  function() {
        alert('Hello World');
    }
};

Common Usage

Combining the use of shorthand results in blocks of code that appear more elegant and easier to read.

var foo = [
    {name: 'apple', prop2: 'test2'},
    {name: 'orange', prop2: 'test2'}
];

Instead of:

function fruit(type, cultivar)
{
    this.type= type;
    this.cultivar = cultivar;
}
var foo = Array(
    new fruit('Apple', 'Fuji'),
    new fruit('Apple', 'Gala')
);

As you can see, using shorthand removes “noise” and reduces the amount of written code, both of which make for easier reading. When rummaging through scripts that contain several hundred lines of code, removing any excess code makes life easier.