19+ JavaScript Shorthand Coding Techniques

Sam Deering
Tweet

improve-your-javascript

This really is a must read for any JavaScript based developer. I have made this post as a vital source of reference for learning shorthand JavaScript coding techniques that I have picked up over the years. To help you understand what it going on I have included the longhand versions to give some coding perspective on the shorts.

Update 05/05/2013 – There are now 19 strong keep em coming! :)

  • Step 1 – Learn the JavaScript shorthand techniques.
  • Step 2 – Save valuable coding time by keeping your code to a minimum.
  • Step 3 – Impress your colleagues with your awesome new coding skillz!

It’s as easy as steps 1,2,3. Here they are.

1. If true … else Shorthand

This is a great code saver for when you want to do something if the test is true, else do something else by using the ternary operator.

Longhand:

var big;
if (x > 10) {
    big = true;
}
else {
    big = false;
}

Shorthand:

var big = (x > 10) ? true : false;

If you rely on some of the weak typing characteristics of JavaScript, this can also achieve more concise code. For example, you could reduce the preceding code fragment to this:

var big = (x > 10);

//further nested examples
var x = 3,
big = (x > 10) ? "greater 10" : (x < 5) ? "less 5" : "between 5 and 10";
console.log(big); //"less 5"

var x = 20,
big = {true: x>10, false : x< =10};
console.log(big); //"Object {true=true, false=false}"

2. Null, Undefined, Empty Checks Shorthand
When creating new variables sometimes you want to check if the variable your referencing for it’s value isn’t null or undefined. I would say this is a very common check for JavaScript coders.

Longhand:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     var variable2 = variable1;
}

Shorthand:

var variable2 = variable1  || '';

Don’t believe me? Test it yourself (paste into Firebug and click run):

//null value example
var variable1 = null;
var variable2 = variable1  || '';
console.log(variable2);
//output: '' (an empty string)

//undefined value example
var variable1 = undefined;
var variable2 = variable1  || '';
console.log(variable2);
//output: '' (an empty string)

//normal value example
var variable1 = 'hi there';
var variable2 = variable1  || '';
console.log(variable2);
//output: 'hi there'

3. Object Array Notation Shorthand

Useful way of declaring small arrays on one line.

Longhand:

var a = new Array();
a[0] = "myString1";
a[1] = "myString2";
a[2] = "myString3";

Shorthand:

var a = ["myString1", "myString2", "myString3"];

4. Associative Array Notation Shorthand

The old school way of setting up an array was to create a named array and then add each named element one by one. A quicker and more readable way is to add the elements at the same time using the object literal notation. Please note that Associative Array are essentially JavaScript Objects with properties.

Longhand:

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

Shorthand:

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 (not naming any names, IE).

5. Declaring variables Shorthand

It is sometimes good practice to including variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time.

longhand:

var x;
var y;
var z = 3;

shorthand:

var x, y, z=3;

6. Assignment Operators Shorthand

Assignment operators are used to assign values to JavaScript variables and no doubt you use arithmetic everyday without thinking (no matter what programming language you use Java, PHP, C++ it’s essentially the same principle).

Longhand:

x=x+1;
minusCount = minusCount - 1;
y=y*10;

Shorthand:

x++;
minusCount --;
y*=10;

Other shorthand operators, given that x=10 and y=5, the table below explains the assignment operators:

x += y //result x=15
x -= y //result x=5
x *= y //result x=50
x /= y //result x=2
x %= y //result x=0

7. RegExp Object Shorthand

Example to avoid using the RegExp object.

Longhand:

var re = new RegExp("\d+(.)+\d+","igm"),
result = re.exec("padding 01234 text text 56789 padding");
console.log(result); //"01234 text text 56789"

Shorthand:

var result = /d+(.)+d+/igm.exec("padding 01234 text text 56789 padding");
console.log(result); //"01234 text text 56789"

8. If Presence Shorthand

This might be trivial, but worth a mention. When doing “if checks” assignment operators can sometimes be ommited.

Longhand:

if (likeJavaScript == true)

Shorthand:

if (likeJavaScript)

Here is another example. 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...
}

9. Function Variable Arguments Shorthand

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.

Longhand:

function myFunction( myString, myNumber, myObject, myArray, myBoolean ) {
	// do something...
}
myFunction( "String", 1, [], {}, true );

Shorthand (looks long but only because I have console.log’s in there!):

function myFunction() {
	console.log( arguments.length ); // Returns 5
	for ( i = 0; i < arguments.length; i++ ) {
		console.log( typeof arguments[i] ); // Returns string, number, object, object, boolean
	}
}
myFunction( "String", 1, [], {}, true );

10. JavaScript foreach Loop Shorthand
This little tip is really useful if you want plain JavaScript and hence can’t use jQuery.each or Array.forEach().

Longhand:

for (var i = 0; i < allImgs.length; i++)

Shorthand:

for(var i in allImgs)

Shorthand for Array.forEach:

function logArrayElements(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9

11. charAt() Shorthand
You can use the eval() function to do this but 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!

Longhand:

"myString".charAt(0);

Shorthand:

"myString"[0]; // Returns 'm'

12. Comparison returns

We’re no longer relying on the less reliable == as !(ret == undefined) could be rewritten as !(ret) to take advantage of the fact that in an or expression, ret (if undefined or false) will skip to the next condition and use it instead. This allows us to trim down our 5 lines of code into fewer characters and it’s once again, a lot more readable.

Longhand:

    if (!(ret == undefined)) {
        return ret;
    } else{
       return fum('g2g');
    }

Shorthand:

return ret || fum('g2g');

13. Short function calling

Just like #1 you can use ternary operators to make function calling shorthand based on a conditional.

Longhand:

function x() {console.log('x')};function y() {console.log('y')};
var z = 3;
if (z == 3) 
{
    x();
} else 
{
    y();
}

Shorthand:

function x() {console.log('x')};function y() {console.log('y')};var z = 3;
(z==3?x:y)(); // Short version!

14. Switch Knightmare

Everyone loves switch statements, *cough*. Here is how you might avoid switch case syndrome.

Longhand:

switch (something) {
 
    case 1:
        doX();
    break;
 
    case 2:
        doY();
    break;
 
    case 3:
        doN();
    break;
 
    // And so on...
 
}

Shorthand:

var cases = {
    1: doX,
    2: doY,
    3: doN
};
if (cases[something]) {
    cases[something]();
}

15. Decimal base exponents

You may have seen this one around it’s essentially a fancy way to write without the zeros. 1e7 essentially means 1 followed by 7 zeros – it represents a decimal base (JS interprets as a float type) equal to 10,000,000.

Longhand:

for (var i = 0; i < 10000; i++) {

Shorthand:

for (var i = 0; i < 1e7; i++) {

16. Decimal base exponents
You can use 1 and 0 to represent true and false. I’ve seen this used in JavaScript game development in shorthand while loops. Note that if you use the negative start your array may be in reverse. You can also use while(i++<10) and you don’t have to add the i++ later on inside the while.

Longhand:

var i=0;
while (i&lt;9)
{
  //do stuff
  i++; //say
}

Shorthand:

var i=9;
while(i--)
{
    //goes until i=0
}

or

var i=-9;
while(i++)
{
    //goes until i=0
}

17. Shorter IF’z

If you have mutiple IF variable value comparisons you can simply ass them to an array and check for presence. You could use $.inArray as an alternative.

Longhand:

if( myvar==1 || myvar==5 || myvar==7 || myvar==22 ) alert('yeah')

Shorthand:

if([1,5,7,22].indexOf(myvar)!=-1) alert('yeah baby!')

18. Lookup Tables Shorthand

If you have code that behaves differently based on the value of a property, it can often result in conditional statements with multiple else ifs or a switch cases. You may prefer to use a lookup table if there is more than two options (even a switch statement looks ugly!).

Longhand:

if (type === 'aligator')
{
    aligatorBehavior();
}
else if (type === 'parrot')
{
    parrotBehavior();
}
else if (type === 'dolphin')
{
    dolphinBehavior();
}
else if (type === 'bulldog')
{
    bulldogBehavior();
}
else
{
    throw new Error('Invalid animal ' + type);
}

Shorthand:

var types = {
  aligator: aligatorBehavior,
  parrot: parrotBehavior,
  dolphin: dolphinBehavior,
  bulldog: bulldogBehavior
};

var func = types[type];
if (!func) throw new Error('Invalid animal ' + type); func();

19. Double Bitwise

The double bitwise trick provides us with some pretty nifty shorthand tricks. Read more about it here: Double bitwise NOT (~~).

Longhand:

Math.floor(4.9) === 4  //true

Shorthand:

~~4.9 === 4  //true

20. Suggest one?

I really do love these and would love to find more, please leave a comment!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.echteinfach.tv/ Harlem

    Thanks for the tips (every programmer should know).

    That was new to me:

    var variable2 = variable1 || ”;

    PS: I dislike Regex just because I cannot read “/d+.+n{0,2}.+s+[A-Z]{2}s+d{5}/m(searchText)” like that… without reference :(
    but I indeed know how powerful it is!

    • http://jquery4u.com/ jQuery4u

      Thanks guys, yeah regex can be hard at first, you get used to it!

    • Miller

      Regex is extremely challenging, but it’s also very necessary. I mean, can you imagine trying to do something like validate an e-mail address? It’s an extremely powerful tool, although I admit I usually can just Google the expression I need rather than try to figure it out myself.

  • http://www.henryschainsawcarvings.com greg

    (just some ideas if you wish to use them) :)
    when you have time, can you show different methods for extracting data from these shortcuts?
    maybe some basic/int/adv uses of ternaries or short circuit logic?
    how to do basic file manipulation in jquery/js – (open edit close [crud]) at the dir>file level?
    how to do string/line basic tasks in js/jquery (open/read/manipulate/save)?
    thanks – suggesting these ideas because you seem to have the most complete js/jquery library on the planet :)

  • Pingback: Interesting links week #28 and #29 - Inside Indivirtual

  • Pingback: 10 JavaScript Shorthand Coding Techniques | Keefr

  • http://eduardodesign.com Eduardo

    Cool!
    This ( var variable2 = variable1 || ” ) i do not know…

  • http://amanjain.com Aman Kumar Jain

    LongHand:
    if(something==True){
    something=False
    }else{
    something=True
    }

    ShortHand:
    something = !something

    • http://jquery4u.com/ jQuery4u

      Thanks Aman, I guess this one is like #8?

  • http://innovatecebu.com aldren niere

    thanks for the post!

    also new to (var variable6 = variable5 || ”; ). this is great!

  • Gary

    I don’t have one to add, but I would like to add some clarity on the topic of ‘associative arrays’. There actually is no such thing as an associative array. What you have is an object and you’re reading its properties: You can access any objects properties in this format object["propertyName"];

    To prove it’s not actually an array, try this:
    var skillSet = {
    ‘Document language’ : ‘HTML5′,
    ‘Styling language’ : ‘CSS3′,
    ‘Javascript library’ : ‘jQuery’,
    ‘Other’ : ‘Usability and accessibility’
    };
    skillSet.push(“PHP”);

    Since skillSet isn’t actually an array, it doesn’t have the array methods (such as push). That’s not to say you couldn’t create an actual array and still set properties and access them the same way (e.g. skillSet["other"])

    • http://jquery4u.com/ jQuery4u

      Nice Gary, i’ve tweaked #4.

  • Tameshwar

    its really nice tips for developer. Thanks for sharing

  • http://seomasterplace.com/ Andru

    Thanks a lot for this note now I go to try shorthand Coding

  • http://www.incredibleinfoway.com Web Development Company Rajkot

    Thanks a lot for this note now I go to try shorthand Coding

  • Pingback: 10 Experimental JS/CSS3 Coding Techniques | jQuery4u

  • http://kali-dasan.blogspot.com kalidasan

    i love your array & assoc array examples.
    Keep good coding.
    Cheers.
    - kalidasan

  • Pingback: A Basic jQuery Plugin using the Module Pattern | jQuery4u

  • http://jquery4u.com/ jQuery4u

    @kalidasan, webdev Raajkot, Andru, Tameshwar, Gary, neire, Aman, Eduardo, Greg, Harlem –

    Thanks guys, much appreciated.

  • http://www.fatihkadirakin.com Fatih Kadir AKIN

    Short function calling:

    function x() {console.log(‘x’)};function y() {console.log(‘y’)};
    var z = 3;
    if (z == 3) {
        x();
    } else {
        y();
    }

    Shorthand:

    function x() {console.log(‘x’)};function y() {console.log(‘y’)};var z = 3;
    (z==3?x:y)(); // Short version!

    • http://jquery4u.com/ jQuery4u

      cool, thanks Akin, i’ll add it to the list!

      • http://www.fatihkadirakin.com Fatih Kadir AKIN

        Thank you! :)

  • Michael_kork

    What about the Array.forEach()? It’s twice as fast as jQuery’s $.each() http://jsperf.com/foreach-vs-jquery-each/9

    • http://jquery4u.com/ jQuery4u

      Hi Micheal Kork, interesting perf thanks for sharing. So hard to read those graphs to read the actual figures but on first glance it does look to perform much faster. I’ve updated the post to reflect this as it does provide a useful shorthand to the standard fo() method.
      Thanks,
      Sam

  • Liam Goodacre

    I believe number 7 to be invalid.

    The following doesn’t work (only tested in Webkit):
    /test/(“is test in here”)

    Correct syntax isn’t used in the longhand, should be something like:
    var searchText, result;
    searchText = “padding 1234 rocket str austin TX 78704 more padding”;
    result = /d+.+n{0,2}.+s+[A-Z]{2}s+d{5}/m.exec(searchText);
    //result: ["1234 rocket str austin TX 78704"]

    Using “new RegExp” is overkill and unnecessary in the shorthand:
    var searchText, pattern, result;
    searchText = “padding 1234 rocket str austin TX 78704 more padding”;
    pattern = /d+.+n{0,2}.+s+[A-Z]{2}s+d{5}/m;
    result = re.exec(searchText);
    //result: ["1234 rocket str austin TX 78704"]

    Given the corrections made, the only difference between the long and short versions is that one caches the regular expression to a variable.  Therefore the entire example serves no purpose.

    Regards,
    Liam Goodacre

    • http://jquery4u.com/ jQuery4u

      Thanks Liam, I’ve updated #7 so it makes more sense.
      Sam

  • Venkat

    Hey, Its really very helpful.

  • Pingback: Useful jQuery Function Demos For Your Projects

  • sc

    Number 2 just saved me a $*&!^ ton of time and code.

    Thank you so much!

    • http://jquery4u.com/ jQuery4u

      Your welcome! ;)

  • Adi

    For #1 you can also do :

    var big = {true: “x>10″, false : “x10];

  • Ted Acres

    Boss

  • Rohit

    Very Helpfull

  • Rajan Rawal

    I learned a lot from your post. its really useful for any web developer. there are some short hand techniques that i was wondering how is it done? but i cleared it here. Thank you

  • Jeff Hansen

    Ensure an object is not undefined/null:

    obj = obj || {};

    • http://jquery4u.com/ jQuery4u

      Hi Jeff, this one is covered in #2! :)

      • matt

        not quite the same as #2… or maybe could be explained better? I use it to ensure obj isn’t cleared if it has already been declared -> var obj = obj || {}; Useful where a function calls it self to loop through a queue. Quick way to avoid undeclared exceptions :)

        • Jónas

          It comes down to the same point, use the variable if it’s at hand, give it a default value otherwise.

  • Anil Kumar

    I liked it. good one !

  • Davide

    Check if an object is not undefined

    longhand:
    if( obj !== undefined) {


    }

    shorthand:
    if(!!obj){

    }

    • http://jquery4u.com/ jQuery4u

      Hi Davide, this one is covered by #2!

  • Davide

    execute some code if condition is valid

    longhand:

    if(obj.checked) {

    function_call(__function_arguments__);

    }

    shorthand:

    obj.checked && function_call(__function_arguments__);

    I love this one ;)

    • http://jquery4u.com/ jQuery4u

      Hi Davide, can you give an example of how to use this one?

      • Miller

        Simple:

        Longhand:
        if(condition){
        doSomething();
        }

        Shorthand:
        condition && doSomething();

        For example:

        if(document.getElementById(‘email’).value == ”){
        alert(‘Please enter an e-mail address.’);
        }

        versus

        document.getElementById(‘email’).value == ” && alert(‘Please enter an e-mail address’);

  • isochronous

    For iterating over the properties of an object:
    for (var prop in obj) if (obj.hasOwnProperty(prop)) {
    console.log(“%s : %o”, prop, obj[prop]);
    }

    • http://jquery4u.com/ jQuery4u

      This one looks cool, whats the longhand version?

  • isochronous

    Or how about this – instead of if (debug) { console.log(“debug message”) },
    you can just use
    debug && console.log(“debug message”);

    • http://jquery4u.com/ jQuery4u

      Good idea mate, doesn’t quite make the list.
      Sam

      • http://www.facebook.com/jimicarlo Jimi Carlo Wills

        Why not?

        as a general item it’s a good idea that you’ve not mentioned in your list… and it’s on a par with #2, which everybody seems to love.

        Both this and #2 are much more important for your list than #3 and #4, which you’ve called “shorthand”, but are actually just literals and are covered in most basic introductory js tutorials.

        ADD THIS! — swap it for #3 and #4!

        In fact, you could expand on it … what() && that(), and success=!what()||!that(), and maybe even success=!!(what()&&that()), or whilst I’m at it… !(what()&&that())&&handleError()

        • http://jquery4u.com/ jQuery4u

          #3 and #4 are still important to those who are learning the ways of coding in JavaScript.

          Also with regards to using !! to negate the value to a Boolean comparison, it’s not good practice I advise using stricter comparison operators such as ==, ===, !== etc… instead. I’m going to write a post about it I reckon.

          • Omid K. Rad

            There are some cases that it makes sense for me to use !!. For example when setting a property that expects a boolean:

            myObject.isAvailable = !!someObject;

            Of course I could do:
            myObject.isAvailable = someObject ? true : false;

            First one is more shorhand, second one is more clear.

    • http://www.opticgait.net tbartels

      Just a warning, IE is finicky about when it will/won’t support the console object, so when testing for it’s presence be sure to use the full namespace resolution:

      > window.console && console.debug(“Debug Message”);

      IE9 has a console object, but ONLY when the F12 developer tools window is open, the JS will break on accessing the console object in the normal browser window, but seem to work correctly when the dev tools are open.

      • http://jquery4u.com/ jQuery4u

        Thanks for sharing mate.

  • http://twitter.com/geekmy GeekRider

    These are awesome! Thanks for sharing!

  • http://www.facebook.com/omidkrad Omid K. Rad

    I think you will like this. When you want to make sure your variable n has a boolean value indicating the existence of something, do like this:

    var n = !!parameter; // n will be true or false depending on if parameter exists or not

    • http://jquery4u.com/ jQuery4u

      Hi Omid, nice idea, had a play around and not sure this works too well. Can you give some examples.
      Thanks,
      Sam

      • sergiu

        var a; var b = 3; a=!!b; // returns a=true

        var a; var b; a=!!b; // returns a=false

        • http://jquery4u.com/ jQuery4u

          Are you sure Sergiu? var a; var b; a=!!b; // returns a=true for me.

          • Omid K. Rad

            @sergiu is correct. Un-initialized declared variables evaluate to undefined.
            !!undefined; // returns false
            !!void(0); // likewise returns false
            var a; !!a; // returns false

      • http://www.opticgait.net tbartels

        It’s called “casting” you are forcing one type of value to convert toanother. if you need to be sure to pass a boolean value to a function or use it for a strict comparison you can cast one type of value to another.

        > var foo = ”;
        > foo == false
        true
        > foo === false
        false
        > !!foo === false
        true

        This is because we are telling the interpreter to make a value judgement on `foo` which actually converts ” to a boolean “!”” which is `true`, but we want the boolean representation of the empty string so we have to “undo” the negation with the second “!”.

        p.s. This is mostly handy if you are strict about practicing good JS habits and always using === rather than ==.

  • Hybrilynx

    i dont know if it matters, but for true and false i just use 0 and 1. like,

    var EnterKey=0; //it equals false

    probably doesnt look that meaningful, but i make games and i really like 0 and 1 over true and false. also since 0 should always be false, you can also, if needed for some reason, say something like this:

    var i=9;
    while(i–){//goes until i=0
    }

    or

    var i=-9;
    while(i++){//goes until i=0
    }

    while loops usually counts up starting with 0, but if not, you dont need to add i–; in the while loop, or even put while(i>0). i dont know if its faster this way, but i just like having shorter codes, instead of codes that works faster.

    you can also use while(i++<10). you dont have to add the i++ later on.

    • http://jquery4u.com/ jQuery4u

      Very nice mate I’ll test it and add it to the list.
      Sam

      • Hybrilynx

        a more reasonable way to use it can probably be this:

        var Cars=['blue car','red car','white car'],
        i=Cars.length;
        while(i–){
        document.write(cars[i]+’, ‘);
        }

        except this will have the array listed backwards. but like i said though, all i really do is make games. something like this would just be used for checking collisions or something. i cant say for sure about just making a normal website.

  • Paul

    if( myvar==1 || myvar==5 || myvar==7 || myvar==22 ) alert(‘yeah’)

    shorter:

    if([1,5,7,22].indexOf(myvar)!=-1) alert(‘yeah’)

    • http://jquery4u.com/ jQuery4u

      Thanks Paul, I guess this could be useful for comparing to a large group of numbers.

      • gmilby

        actually, it’s very useful (Paul’s suggestion)… think about it – it’s easy to push into in array, but getting backed into an endless ‘if’ or case statement really blows…
        Paul’s suggestion would allow the array to remain dynamic – and handled regardless – good suggestion :-D

    • http://jquery4u.com/ jQuery4u

      Added #17.

  • bruce

    # 7 with inline regex there are performance degradations :) check jsperf.

  • etb

    is var something?

    if (!!var) {
    // do something
    }

    • http://jquery4u.com/ jQuery4u

      Hi etb, not really, if I am correct it converts the value of var to a primative boolean value (as opposed to a loosely value such as NaN, undefined, etc)… kind of like Boolean() typecast but this created an object type not a true boolean. Also I think it is not used much as some browsers react badly to it.
      Sam

      • Omid K. Rad

        Good point. I didn’t think of Boolean() typecast.

  • http://twitter.com/NasserAlmanji NasserAlmanji

    Thanks

  • Pingback: 50 jQuery Function Demos for Aspiring Web Developers - Smashing Coding

  • http://jquery4u.com/ jQuery4u

    Yeah I never use it but it is a shorthand method.

    • http://www.martinhansen.no Martin Hansen

      Should not be used for arrays. Not for looping over the array anyway. Which is what most people wants. Consider this:
      var arr = ['apple','orange']; arr.foo = 5;
      for(var i in arr){console.log(i)}

      outputs
      0
      1
      ‘foo’

  • http://jquery4u.com/ jQuery4u

    Nice, thanks John.

  • http://www.facebook.com/mohammed.mansoor.33449 Mohammed Mansoor

    gud piece of code :)

  • Tokimon

    Hi

    #10: i propose:
    for (var i = allImgs.length; i–;)

    the reason is that your shorthand method indexes the properties/items in the array before looping. My proposed method just saves the number of items in the index variable and then continues untill it reaches 0, just like with the while loops. And counting is faster than indexing.

  • Your Example Is Wrong

    I was just reading this, and example 4 is 100% incorrect. You want to do `var skillSet = new Object();` ***NOT*** `new Array()`. JavaScript doesn’t have associative arrays. That example only worked because everything in JavaScript is an object that can have properties. Please know that JavaScript has numeric arrays and objects, it does NOT have associative arrays.

  • bozma88

    Shortest and safest inline IF construct:

    ( cond && doSomething() );

    Is this correct?

  • bozma88

    Well.. even:

    cond && doSomething();

    seems fine.

  • Daniel Cox

    This list has a few inaccuracies. Since I’m feeling lazy, I’m only going to mention #2 for now.

    The operator you used in your shorthand (||) is called the default operator, and the longhand version has some different implications from the shorthand version. So, I don’t believe you and you shouldn’t believe you either.

    Take your examples and use any falsey value that you haven’t considered. In this case, I’ll use 0.

    //unconsidered falsey value example
    var variable1 = 0;
    var variable2 = variable1 || ”;
    console.log(variable2);

    Go ahead and try it out and check the output. You got an empty string, didn’t you? Interesting, because according to your longhand variable2 should have had a value of 0.

    I’m not trying to make you look bad, in fact I applaud that you are trying to educate people, and as such you should also be educated first.

    Hope this helps!

    • http://hybrilynx.net/ Hybrilynx

      using the bitwise thing ~ mentioned above (depending on the disqus settings), you could use #17 as the alternative shorthand, with:

      var variable2 = ~[undefined,null,false].indexOf(variable1) ? ” : variable1;

      and it should solve anything you want. well, as long as you just put what you dont want in that array. so now if var1 is 0, var2 becomes 0 too. but hey, if you want var2 to become false if var1 is false for whatever reason, you can just take it out of the array and leave it as [undefined,null]. or if you want var2 to equal ” if var1 is 0, just add 0 in the array.

  • Connor Miles

    You can even shorten this if([1,5,7,22].indexOf(myvar)!=-1) alert(‘yeah baby!’);

    to this

    if(~[1,5,7,22].indexOf(myvar)) alert(‘yeah baby!’)

    • gmilby

      just noticed the tilda – what’s that providing?

      • Connor Miles

        whats `tilda`? i didn’t understand that at all

        • gmilby

          this squiggly line in the if statement:

          if( —> ~ <— [1,5,7,22].i…

          thanks for replying!

      • Daniel Cox

        The tilde is a bitwise NOT, as opposed to the logical NOT operator (the ! operator). Since the indexOf method will return a -1 if “myvar” isn’t found in the array literal, the tilde performs the bitwise NOT, converting that -1 into a 0. Since 0 is a falsey value, the alert will fire. That said, in my opinion this is a shorthand that reduces the readability of the code for very little gain.

    • http://hybrilynx.net/ Hybrilynx

      or pretty much anything that returns a -1. like .search();
      i like this though becuz sometimes i use indexOf() pretty often. i use to use indexOf() < 0 but ~indexOf() looks alot better.

  • gmilby

    this saved my rump today… it’s underscore, but remove the wrapper, and logic works standalone also!

    _.mixin({
    findKeysByValue : function(object,value) {
    var retVal=[]
    for(var key in object){
    var obj=object[key]
    if(obj==value){
    retVal.push(key)
    }
    }
    return retVal;
    }
    });

    • Daniel Cox

      Keep in mind that doing a for..in loop has its own set of implications, because it iterates over all of the properties in the prototype chain. You’ll want to add a call to the hasOwnProperty() method to make sure you are looking at a property of this object itself.

  • http://hybrilynx.net/ Hybrilynx

    for number 1

    var big = (x > 10) ? true : false;

    can just be,

    var big = x > 10;

    but of course, you cant do the extra stuff like making the var big get a custom value though. but it would make var big equal true or false.

  • likemandrake

    Simple operations on some value, but only when it’s not boolean false:

    var tag = ‘a';
    tag = tag && ” || ”;

    or other example:

    var firstName = ‘My’,
    lastName = ‘Name';

    name = firstName + (lastName && ‘ van ‘ + lastName || ”);

  • likemandrake

    Fastest way iterations on arrays, but when order isn’t important:

    for (var a = [0, 1, 2, 3, 4, 5], i = a.length; i–;) {
    console.log(a[i]);
    }

  • likemandrake

    Equalivent to:

    var big = (x > 10) ? true : false;

    is:

    var big = x > 10 && true : false;

  • likemandrake

    Fast way convert value to boolean is:

    !!value;

    • likemandrake

      instead of:

      if (value) {
      value = true;
      } else {
      value = false;
      }

      • Omid K. Rad

        That would be:
        value = !!value;

  • erata61

    good article. thanks.

  • scryber

    “$(‘#news :checked’)”

  • Panagiotis Tzam

    For #2 you will still get an undefined error if the variable is not defined anywhere in the code. To prevent this I have found that only:
    typeof undefinedVar !== “undefined”
    is working

  • Mohammed Joraid

    Nice article.
    But in (Associative Array Notation Shorthand) it’s not an array anymore, it’s an object.

  • Paul

    For the “var big = (x > 10) ? true : false;” example, why even use a ternary operator? (x>10) evaluates to bool, so you can just use “var big = (x>10);”

    • Paul

      In the first example.

  • elidiota

    hi, thanks for the article, The double bit wise is great!

    surely you know but

    shorthand for true = !0
    shorthand for false = !1
    shorthand for undefined = void 0

  • Jordan Alexander

    Shorthand function, available in FireFix, ES6 and something else.. I can’t rememeber.

    someFunction(function(x) {
    //code
    });

    =

    someFunction((x) => {
    //code
    });

    Slightly shorter, less browser compatibility, but still works.

  • Raven Lagrimas

    assign a value and make use of its return value:

    var x, y, sum;
    console.log(sum=(x=1)+(y=2));
    // x = 1, y = 2, sum = 3

    use && for single if statements:

    if(a){
    console.log(a);
    }

    to

    a && console.log(a);

    assign local variables with the same values.

    var c, b, a = b = c = 0;

    // every variable will remain local and equal to 0;

  • Pingback: Useful jQuery Function Demos For Your Projects - Internet Business

  • lordtubington

    How would I shorten this?

    function monsterLevelCalc() {
    var level, sac, cost;
    level = document.getElementById(“monsterLevel”).value;
    sac = document.getElementById(“monsterSac”).value;
    cost = 0;

    // simple validation
    if (level === null || level === “” || sac === null || sac === “”) {
    alert(“Please fill out Monster Level and # of Monsters to Sac”);

    return false;
    } else if (sac > 10) {
    alert(“# of Monsters to Sac should be no greater than 10″);
    return false;
    } else if (level > 199) {
    alert(“Monster Level should be no greater than 199″);
    return false;
    }

    level*=1;
    sac*=1;
    cost = -5 * (level + 1) * (sac – 21) * (sac);
    document.getElementById(“goldCost”).innerHTML = cost;
    }

  • Sameer

    Point #16 is having incorrect heading.
    For #19, bitwise operations are effeciencywise slower in javascript, so although longhand, Math.floor seems to be more efficient.
    #14 and #18 are basically the same.
    #10 is totally wrong (will work only in case of arrays of consecutive no.s starting from 0). Basically ‘for i in myArray’ will iterate over the indexes and not the values in myArray.
    #12: The shorthand is checking for any truthy value instead of strictly checking against null, 0, NaN, false, [], {}, ” and undefined.
    They are not the same. Same for #8.
    #9: The shorthand will be strictly discouraged, as it’s very bad in terms of readability and maintainability. It’s a very bad practice.

    • Sam Deering

      Thanks for your feedback Sameer.

  • Banana Man

    Longhand:

    “I’m going to use every cool code shortening trick I know to write 1337 code regardless of maintainability”

    Shorthand:

    “Fail”.

    • Gabo Lugo

      Hahahahaha nice.

    • Sam Deering

      LOL! Good one.

  • nicolausai

    i tried to add a value inside an array with this notation but didn’t work:
    var array = [];
    var array[] = ‘value';
    what i wanted to do was add an index->value pair inside the array without specifying the index
    finally used .push

  • http://nampnq.vietnamcode.info Nam Phạm Ngọc Quang

    Longhand:

    if(x){
    y()
    }

    Shorthand:
    x && y();

  • james123

    Unless your checking agents a number and if its not 0 then set as a something.. so its not really a bug its just a tool and if used wrong doesn’t do what its suppose to.

  • Sam Deering

    I only use this really for namespace assignment (checking if an object exists or not).