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.


31 Responses to “Javascript shorthand for cleaner code”

  1. […] Javascript shorthand for cleaner code […]

  2. Charl van Niekerk » Blog: JavaScript Shorthands says:

    […] response to Javascript shorthand for cleaner code, there are ways you can make your code even more […]

  3. mrlagmer says:

    Thanks. I always had trouble understanding the Ternary operator this makes more sense now.


  4. Dylan says:

    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.

  5. Dennis says:

    These also work in PHP, in fact I use


  6. […] – Javascript shorthand for cleaner code “A few ways to save on some bytes in your Javascript code, as well as making it more readable […]

  7. Craig says:

    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’);


  8. Emma says:

    @Craig – thanks for pointing that out, I’ve updated the example.

  9. Default assignments was new. Thanks for pointing that out.

  10. Paul Datta says:

    This information might be redundant for some people but I am happy its here as a lot of us could use it. Neat.

  11. eL Abee says:

    I am new to Javascript, this shorthand very usefull! thanks

  12. Sam Dalton says:

    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.

  13. William says:

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

  14. Alex says:

    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.

  15. Alex says:

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

    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.

  16. Atika says:

    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.

  17. […] from: Punkchip | Javascript shorthand for cleaner code 25 May 2010 | Uncategorized | Trackback | | Stumble it! | View Count : 0 Next Post […]

  18. m3talsmith says:

    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.

  19. @Craig: You can use it like this
    var navigation = $(‘.main-nav’).length ? $(‘.main-nav’) : $(‘.secondary-nav’);

  20. Roman says:

    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.


  21. Emma says:

    @Roman – thanks my bad with the example, I’ve updated the text.

  22. Joep says:

    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.
    //check if window has a method named DrawPie
    if(!!window.DrawPie) window.DrawPie();

  23. Iain Doughty says:

    Nice little set of short hand for JS, just what I was looking for to optimise my code some more.

  24. […] Javascript Shorthand for Cleaner Code – Emma Sax […]

  25. McNugget says:

    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.

  26. Erika Rendon says:

    $updateScript .= ‘f00’;

    I was looking for the DOT appending method like PHP

  27. Pat says:

    This works with objects as well.
    console.log = console.log || function () { };

  28. […] Javascript shorthand […]

  29. fdfd says:

    It’s a misconception to think that this is going to simplify the code to people reading it. x = x+1 will always be more explicit than x++. Read the book clean code by Robert Cecil Martin if you are serious about making your code more readable.

  30. Punk Chimp says:

    Stolen from Site Point.

    You clearly don’t understand JavaScript as the Array() section is incorrect (probably why you stole it from SitePoint).

  31. Rob says:

    Taking the ternary example, would it not be even more succinct to do the following, seeing as the condition already returns a boolean?

    var canDrink = (myAge > legalAge);

Leave a Reply