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.

26 comments on “Javascript shorthand for cleaner code”

  1. Pingback: Charl van Niekerk » Blog: JavaScript Shorthands
  2. Nice tips Emma.

    Seeing as you’re either going to get true or false with that ternary, you could simplify it further:

    var canDrink = (myAge >= legalAge);

    I don’t think the parentheses are required there, but it helps with readability a little bit imho.

  3. Cool article.

    One quick thing. Your default assignments example won’t do as intended in jQuery because $() will always return a jQuery object even if ‘.main-nav’ isn’t found. That jQuery object will always evaluate to true.

    var navigation = $(‘.main-nav’) || $(‘.secondary-nav’);

    Craig

  4. It might be good to explain that || is in fact the OR operator, and not a piece of syntax used solely for achieveing a default function parameter.

    Other than that, some great tips for those new to programming.

  5. Such a great tip… I have never used default assignment short code before… Nice and simple explanation. Thx for sharing again

  6. It might also be worth pointing out how the “Default assignments” works.

    It works just like `if (myVar == 1 || myVar == 2)` in that if the left hand equates to true, it skips the right hand because only one needs to be true for ‘or’ to be true. If it evaluates to false, then it will check the other side, and because of the way JavaScript returns expressions, it gives the right hand value.

    Be warned though, if one or your arguments can be FALSE then it will always give the right hand side.

  7. Oh, and here it is on JSbin if you want to see what I’m talking about.

    http://jsbin.com/ahaya/edit

    Sorry I didn’t say it before, but this is a good list of techniques, thanks for the article. I wish I had read them compiled like this when I started JavaScript programming.

  8. Thanks, very useful technics. I do not yet know the «double pipe» technics. It’s true that sometimes I don’t think to use this programming technics to simplify my code.

  9. I use the ternary operator often. It’s one of the most useful shorthands available and it’s available in almost every language, so once you’ve learned the technique, you can use it almost anywhere.

  10. Just wanted to point out one pitfall with the default value:

    if you want to be the limit explicitly 0 it doesn’t work as desired:

    var limit = 0;
    var length = limit || 10;
    console.log(length); // displays 10 instead of 0

    so you always have to be careful with this one.

    greets

  11. Here’s a nice one; to check if an object is set to any truthy value (i.e. not nothing/null) present (useful for browser specific things as ActiveX): !!object
    The first negation causes the value to become a boolean, the second inverts it.
    Example;
    //check if window has a method named DrawPie
    if(!!window.DrawPie) window.DrawPie();

  12. Hello Emma. I’d like to comment on the array notation section because it has the potential to be quite misleading to someone new to javascript.

    In both examples, you are assigning properties to an object, not filling out an array, yet the object is explicitly declared as a new Array() in the first example while array contents are never assigned. skillSet[0] would return undefined, not “HTML5″, because the array itself is still empty.

    The shorthand for creating an array is square brackets and the shorthand for an object is curly braces, which is what you use in the second example. The second example is probably what you intend to be creating, though (a general object with properties). It is not actually the same result as the first example (an empty array with properties). To make them match, the first example would have to begin with “skillSet = new Object()” instead of “skillSet = new Array()”.

    In JS, all objects are effectively ‘associative arrays’, but it’s confusing to speak of them as such. An array or array-like object in javascript is always an object on which methods like .push(), .pop(), splice(), .length(), etc make sense.

Add your comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>