Javascript shorthand for cleaner code

Translation: Croatian

A few ways to save on some bytes in your Javascript code, as well as making it more readable and quicker to write:

Variable increment/decrement/multiply/divide

When you want to increase or decrease a number variable by one; instead of this:

growCount = growCount + 1;
shrinkCount = shrinkCount - 1;

You can simply do the following:

growCount ++;
shrinkCount --;

Or to add/subtract/multiply/divide a number to/from/by itself you can do:

growCout += 100;
shrinkCount -= 2;

moreSweets *= 5; // multiply moreSweets by 5
lessApple /= 2; // divide lessApple by 2

Ternary operator (conditional)

This is a great code saver for when you want to do something if the test is true, else do something else:

if(myAge > legalAge) {
    canDrink = true;
else {
    canDrink = false;

Instead, put the condition before the question mark then the if true statement and false statement after that separated by a colon:

var canDrink = (myAge > legalAge) ? true : false;
As pointed out in the comments, the above example can be further simplified to var canDrink = myAge > legalAge because it’s returning a boolean.

Associative array notation

The old school way of setting up an array was to create a named array and then add each named element one by one:

var skillSet = new Array();
skillSet['Document language'] = 'HTML5';
skillSet['Styling language'] = 'CSS3';
skillSet['Javascript library'] = 'jQuery';
skillSet['Other'] = 'Usability and accessibility';

A quicker and more readable way is to add the elements at the same time using the object literal notation to become:

var skillSet = {
    'Document language' : 'HTML5', 
    'Styling language' : 'CSS3', 
    'Javascript library' : 'jQuery', 
    'Other' : 'Usability and accessibility'

Don’t forget to omit the final comma otherwise certain browsers will complain.

Default assignments

The following is useful if you are testing if a variable has previously been set and if not to try something else:

function displayValues(limit) {
    var length;
    if(limit) {
        length = limit;
    } else {
        length = 10;
    for(var i = 0; i++; i < = length) {

A shorter way is to use the double pipe. If limit has not been passed to the function then length will be set to the default of 10:

function displayValues(limit) {
    var length = limit || 10;
    for(var i = 0; i < = length; i++) {
The variable length will be set to the value of the left operand if it evaluates to true, therefore anything other than the following:

  • false
  • 0
  • null
  • undefined
  • empty string

Otherwise it will be set to the value of the right operand. So this isn’t the right thing to use if you need to explicitly set the length to zero.