By Sam Deering

19+ JavaScript Shorthand Coding Techniques

By Sam Deering


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.


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


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.


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


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  || '';
//output: '' (an empty string)

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

//normal value example
var variable1 = 'hi there';
var variable2 = variable1  || '';
//output: 'hi there'

3. Object Array Notation Shorthand

Useful way of declaring small arrays on one line.


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


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.


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


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.


var x;
var y;
var z = 3;


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).


minusCount = minusCount - 1;


minusCount --;

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.


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


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.


if (likeJavaScript == true)


if (likeJavaScript)

Here is another example. If “a” is NOT equal to true, then do something.


var a;
if ( a != true ) {
// do something...


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.


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().


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


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!




"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.


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


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.


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


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.


switch (something) {

    case 1:

    case 2:

    case 3:

    // And so on...



var cases = {
    1: doX,
    2: doY,
    3: doN
if (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.


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


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.


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


var i=9;
    //goes until i=0


var i=-9;
    //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.


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


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!).


if (type === 'aligator')
else if (type === 'parrot')
else if (type === 'dolphin')
else if (type === 'bulldog')
    throw new Error('Invalid animal ' + type);


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 (~~).


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


~~4.9 === 4  //true

20. Suggest one?

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

  • 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!

    • 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.

  • (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()

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

  • LongHand:

    something = !something

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

  • 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’

    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”])

    • Nice Gary, i’ve tweaked #4.

  • Tameshwar

    its really nice tips for developer. Thanks for sharing

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

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

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

  • i love your array & assoc array examples.
    Keep good coding.
    – kalidasan

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

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

    Thanks guys, much appreciated.

  • Short function calling:

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


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

  • Michael_kork

    What about the Array.forEach()? It’s twice as fast as jQuery’s $.each()

    • 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.

  • 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.

    Liam Goodacre

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

  • 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!

  • Adi

    For #1 you can also do :

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

  • Ted Acres


  • 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 || {};

    • 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

    if( obj !== undefined) {




    • Hi Davide, this one is covered by #2!

  • Davide

    execute some code if condition is valid


    if(obj.checked) {




    obj.checked && function_call(__function_arguments__);

    I love this one ;)

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

      • Miller



        condition && doSomething();

        For example:

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


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

    • 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”);

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

      • 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()

        • #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.

    • 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.

  • These are awesome! Thanks for sharing!

  • 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

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

      • sergiu

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

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

        • 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

      • 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
        > foo === false
        > !!foo === false

        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


    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.

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

      • Hybrilynx

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

        var Cars=[‘blue car’,’red car’,’white car’],
        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’)


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

    • 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

    • Added #17.

    • Daniel Díaz Benito

      It is perhaps more clear for you to use instead:

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

  • bruce

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

  • etb

    is var something?

    if (!!var) {
    // do something

    • 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.

      • Omid K. Rad

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

  • Thanks

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

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

    • 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’]; = 5;
      for(var i in arr){console.log(i)}


  • Nice, thanks John.

  • gud piece of code :)

  • Tokimon


    #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.

    • David Turner

      Quite right, this author is clearly no expert.

    • Gaby

      The following gives the wrong answer
      var skillSet = new Array();
      skillSet[‘Document language’] = ‘HTML5’;
      skillSet[‘Styling language’] = ‘CSS3’;
      skillSet[‘Javascript library’] = ‘jQuery’;
      skillSet[‘Other’] = ‘Usability and accessibility’;

      The methods do not give the desired information.

  • 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 || ”;

    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!

    • 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.

    • The shorthand is used for checking gainst null / undefined or empty, not getting the value of another variable, so nothing is wrong, and you shouldn’t use it for all cases.

  • 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.

    • 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.

    • Daniel Díaz Benito

      If you do not need to retrieve the index value, just use:

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

  • gmilby

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

    findKeysByValue : function(object,value) {
    var retVal=[]
    for(var key in object){
    var obj=object[key]
    return retVal;

    • Daniel Cox

      Keep in mind that doing a 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.

  • 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–;) {

  • likemandrake

    Equalivent to:

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


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

    • this throws error, shorthand is
      var big = x > 10 && true;

  • likemandrake

    Fast way convert value to boolean is:


    • 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

    • berkana

      For some of these, I don’t know if the savings of a couple of characters is worth the additional calculation behind the scenes, nor the potential confusion and obfuscation of the intent of the code.

    • 1 up for `void 0`

  • Jordan Alexander

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

    someFunction(function(x) {


    someFunction((x) => {

    Slightly shorter, less browser compatibility, but still works.

  • Raven Lagrimas

    assign a value and make use of its return value:

    var x, y, sum;
    // x = 1, y = 2, sum = 3

    use && for single if statements:



    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;

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

    • Jay Hubert Tauron

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

      // simple validation
      if (!level || !sac) {
      alert(“Please fill out Monster Level and # of Monsters to Sac”);
      } else if (sac > 10) {
      alert(“# of Monsters to Sac should be no greater than 10”);
      } else if (level > 199) {
      alert(“Monster Level should be no greater than 199”);
      } else {
      document.getElementById(“goldCost”).innerHTML = -5 * (level + 1) * (sac – 21) * (sac);

      i know im like 8 months late lol

  • 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.

    • I know this comment is really late to the party, but after testing the bitwise operation, it does not seem to be slower than Math.floor (at least, not in Firefox). Using the following function to determine the average speed of functions:

      function s(n) {
      for(var i = 1; i < arguments.length; i++) {
      var start, total = 0;
      for(var j = 0; j < n; j++) {
      start =;
      total +=;
      console.log(arguments[i].name + ': ' + (total/n) + 'ms');

      And the following two test functions:

      function bwise () { return ~~4.9 === 4; }
      function floor () { return Math.floor(4.9) === 4; }

      The following call:
      s(1e6, floor, bwise);

      … consistently yielded results where bwise executed ~2x as fast as floor (~0.00043ms vs ~0.00023ms). Maybe this is just optimizations in Firefox?

    • Neil Monroe

      For #9, this format can be used if you which to make several signatures for your function (and not write separate functions). Say, you want to call it with an optional second parameter that when not present, shifts the expected arguments. I understand the readability concerns since if there is no documentation as to the usage of the function, the programmer would have to examine the code. A caveat with this method also is that the types of arguments becomes more important because they are being checked for presence.

    • #9 is useful in terms of number of arguments, when number of arguments varies.

  • Banana Man


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



    • Gabo Lugo

      Hahahahaha nice.

    • Sam Deering

      LOL! Good one.

    • Marc

      Hahaha. Personally I disagree: Short hand patterns are easier to read since a human can much more easily grasp the shorter code as a pattern. So code reading should be faster.

      • Maciej Sawicki

        I think the code reading may be slower with shorthand versions.
        Human eyes are better in “scanning” text and understanding the rough idea based on smaller parts of the text. Shorthand versions demand reading every symbol carefully and the chain of dependencies may become too buried with more complicated things. Also if someone doesn’t know this particular shorthand it makes the code slower to read because he needs to look up what it means and learn the new pattern.

      • mManishTrivedi

        M not agree with you. Its totally personal choice. :)

      • Sebastien Henri

        Reading code and understanding code are two different things ;)

  • Minh Tran

    For the tip #15, there is a typo. It should be 10000 = 1e4 instead of 1e7

  • 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

    • Well, your mistake is that you declared array again. Your code written correctly would be:
      var array = [];
      array[] = ‘value’;

  • Longhand:


    x && y();

    • SWR

      Even better, we can call multiple functions if they are comma delimited inside parenthesis :)

    • Nguyễn Trình

      agree with you

    • An Đức

      Vietnam every where :3

    • Jen

      Can someone explain?

      • Юлій В. Чирков

        in brief, elements of conditional expression are checked for trueness from left to right, if some elm (1st, 2nd, 3rd, 4th et cetera) fails, the interpreter won’t check the rest, since for conditional expressions there a priory is the dogma «one piece failed = the whole failed» implied by the logic of conditional expression per se

        x && y() is a kinda conditional expression «if x is truthy and y() is truthy» (i.e. not undefined, not null, not negative & not zero — if x is number, it gotta be positive, if sting — contain at least 1 char, if array — at least one element etc)». so, when interpretter finds x = truthy, if goes along w/ check of the next part of expression, i.e. y(). since y() is function, it can’t be interpretted as truthy or falsy as is, so interpretter is forced to exec the function to find out its return

        but the trick is indeed we don’t care if x && y() is truthy or falsy, we just use the logic flow of this check to have our fn executed under certain conditions w/o extra code overgrowth

        sometimes this mehtod is really useful & can be much more complex

        as example here is small fn from my js helper tools set, it takes some other fn as argument & runs it again & again in n iterations w/ pause after each run (the number of iterations & pause period in miliseconds are also passed as arguments; beyond that in arguments along with function to run you can also pass some concrete context for the execution, as long as any number of arguments to pass to your fn on the run)

        var ripple = function (ms, itr, fn, ctx) {
        ctx = ctx || this
        var rptr = function () { !itr || (–itr, fn.apply(ctx, [], 4)), setTimeout(this.rptr.bind(this), ms)) }
        return rptr

        as you see, we anyway gotta check if the context had been passed in arguments along w/ function or not since we need it a little later, but an extra unwanted ramification like «if (ctx !== undefined && ctx !== null) {…}» can be easily avoided w/ expression ctx = ctx || this

        there’s no need to declare ctx thru var ’cause it is already declared in fn arguments, but if there’s been no need in special context for the passed function, this argument could be ommited thus ctx can contain void 0, which is unacceptable for our flow — so we use conditional expression «ctx = ctx || this» to have ctx linked to some concrete context for sure. the expression is like «if ctx has been linked to some context, just leave it as is, otherwise link ctx to current one»

        the logic is — if context matters, it would be linked to ctx in arguments, thus ctx per se will be truthy. but if ctx is falsy, hence, the context is unimportant & we can use any, including our current. same trick w/ conditional expressions as the first one, but this time instead of «and» we use other logical operator — «or»

        another final short example — if you’re sick & tired of monstrosity like if (someString.indexOf(someWord) !== -1) {…} or if (someArrayWithSomeEntries.(someWordOrNumber) !== -1) while checking if some item belongs to a string or an array, you can replace both constructions above w/

        ~someStringOrArray.indexOf(someItem) &hope it helps

      • Alexandre Borela

        && is the “and” operator and stops as soon as one of the expressions evaluates to false. So if the left expression “x” evaluates to false, the right expression “y()” will not be checked.

  • Phu

    Regarding #17: how do you ass something in JavaScript?

    • Neil Monroe

      You could go the extra step and make it:
      if(!~[1,5,7,22].indexOf(myvar)) alert(‘yeah baby!’)

    • Neil Monroe

      You could go the extra step and make it:
      if(!~[1,5,7,22].indexOf(myvar)) alert(‘yeah baby!’)

      • Daniel Díaz Benito

        What about:
        if(myvar in [1,5,7,22]) alert(‘yeah baby!’)

  • Dmitry

    var x = variable1 || ”;
    This is an example of a very bad shorthand and a bugs magnet. If variable1 happens to be a 0(zero) on purpose this shorthand will evaluate it as false and replace with something that is not supposed to be there.

  • toddpress

    On no 17, you could leverage bitwise and logical operators for the in-array shorthand. Ex: !!~[1,5,7,22].indexOf(1) && alert(“sweet”); This is cool if you like unreadable one-liners, because it both shortens the “exists within” computation AND removes the “if” statement completely.

  • WFK

    Suggest updating #15 to read i < 10,000,000 so that the longhand and shorthand match.

  • CoDEmanX

    Beware of ~~ if you deal with large numbers, implicit casting is done to 32bit int (whereas numbers are 64bit float in JS) and you may thus screw up your number by overflowing. Nicer shorthand: 4.9 | 0 // result: 4

  • 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).

  • Jay Hubert Tauron



    will both return integer

    • ArtBIT

      Bare in mind though:

      parseFloat(“”) != +””
      parseFloat(“1A”) != +”1A”

  • Abdelwahab Bounasser

    // longhand.
    if ( str.indexOf(ndx) == 0 ) {
    // char not found.

    // shorthand
    if ( ~str.indexOf(ndx) ) {
    // char not found.

  • Vineet

    Its very useful.

  • berkana

    Here’s one I learned today. If a value needs to be typecast as a boolean, the long-hand way would be to type Boolean(value) where value needs to be typecast. Boolean will return true if value is truthy, and false if value is falsy. But this will do the same: !!(value)

  • Kirill Sinelnikov

    var likeJavaScript = [0]
    if (likeJavaScript == true) alert(“I’ll never be shown”)
    if (likeJavaScript) alert(” And I’ll be”)
    Be careful with ==

  • numediaweb

    $.each([1,2,3], function(index, variation) {
    var active = (index === 1) ? ‘active’: ” ;
    html_bar += ‘bar’;

    Short hand:

    $.each([1,2,3], function(index, variation) {
    html_bar += ‘bar’;

  • lookfortheroot

    Please fix big fonts in some places on page, it’s hard to read.

  • Awesome!!! Thanks!!!

  • Michael

    Deciding which function is defined.

    Long Hand:

    function recurse (arr, update, cb) {
    if (arr.length < 1) {
    // call cb if defined, otherwise call update
    if (cb !== undefined) {
    return cb();
    return update();

    // do stuff with arr

    return recurse(arr, update, cb);

    Short Hand:
    function recurse(arr, update, cb) {
    if (arr.length < 1) {
    return (cb || update)(); // call cb if supplied, otherwise call update


    // Do stuff with arr

    return recurse(arr, update, cb);


    This isn't a great example, but hopefully you get the point.

  • berkana

    I find that I have to convert the Arguments array-like object into an actual array often enough that I’m often doing this:

    var argsArray =;

    What this does is makes an array copy of the arguments array-like object using the slice method. However, since the slice() method belongs to arrays, it is stored on the Array.prototype object, and has to be applied to arguments using the call() method. Fortunately, there is a much shorter way to get the same effect:

    var argsArray = [];

    slice() is a method found on all arrays, which inherit this method from Array.prototype, so calling it from an empty array literal works just as well.

    • B.Max

      Or Array.from(arguments) as of ES5.

  • Nice article!

    I would report some little bugs:
    * Bigger text on half of article content,
    * 15. Decimal base exponents -> longhand should be that 10,000,000
    * 16. Decimal base exponents -> longhand – “<” instead “<"

  • DHebbes

    Be careful using this method #14 of shortening switch statements (which is actually not shorter, cleaner).

    Its 60% slower in terms of operations, check out the perf test

  • borto matheo

    if ( “a”.indexOf(“arrow”) >0){}


    if (~ “a”.indexOf(“arrow”){}

    it works for all function witch return -1 to say false because ~x = – x -1 and ~-1=0






    Longhand while(1){}

    ok lol for 1 letter


    the example with switch is no optimal here my way :

    Longhand swtich(a){
    case1: f1()break;
    case2: f2()break



    var cases = [
    var a = cases[something])
    a && a();// when i have twice the same think i prefer use && instead of if

    Longhand :




    b = a && 5;

    warning b == false if not a,

    but you can use || for else if

    Longhand :



    ~function(){alert()}() works too with + or – or !

    imagine a1 change the value of a and b1 change the value of b but don’t retrun it


    var c;


    c = a





    shortand: with the operator “,” coma that return the last

    var c = (a1(),a) || (b1(),b);

    with coma opérator and && and || and () you can completly remove if else but only do this if it stay readable




    you can use coma in while loop, the last is the condition ex:



    cond = myFunc(i);


    you can create shorcut of function with bind
    long :
    function find(){
    return aString.indexOf(anOtherString)

    shorter: find = aString.indexOf.bind(aString,anOtherString)

    — and please don’t use for in you will go throught inherted property of prototype an alternative is object.keys or array.forEach

  • borto matheo

    it is php this notation doesn’t exist in js

  • Simeon

    Swapping Variables

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


    • Simeon

      You can also use it to turn code into a 1 liner

  • jkk

    Instead of
    var x = function(s){ alert(s); }
    function x(s){ alert(s); }
    var x=s=>{ alert(s);}

    • n

      This will work only on Mozilla.

      • B.Max

        Nope, on all ES6 mostly-compatible browsers, including Opera, Chrome and Edge.

  • Nick Dugger

    There’s sooo much really bad practice in this post. I suggest removing it or rewriting it. Really, it just makes me cringe.

  • Nick Smith

    The shorthand for #2 can still work inside the if, quite useful to test and protect against undefineds. if( (test || ”) === someVar) { stuff; }. This can also work with functions if( Number.isInteger(test || ”) ). Helps alot ( I wonder if it will help my Java NPEs!)

  • ArtBIT

    Some bitwise tricks:


    Math.floor(4.9); // 4


    4.9 | 0; // 4

    XOR Swap

    var a = 1;
    var b = 2;
    var tmp = a;
    a = b;
    b = tmp;


    var a = 1;
    var b = 2;
    a^=b, b^=a, a^=b;

    Integer division by the power of two




    Check if variables have the same sign

    Math.sign(x) == Math.sign(y);


    (x ^ y) >= 0;

    Toggle between two values

    if (x == a) {
    x = b;
    } else if ( x == b ) {
    x = a;

    // x = 1, a = 1, b = 2
    // 1st run: x = 2
    // 2nd run: x = 1
    // 3rd run: x = 2
    // 4th run: x = 1
    // ...


    x = a ^ b ^ x;

    …and more

    • B.Max


  • Mistefiks

    Article has weird problems with the formatting in JS code but it’s still great. :)

  • #1. var big = x > 10.

  • blacmoon

    Thanks… Author…

  • Orlando Mamani

    What does mean?
    var x = ( y(), z() );

    • B.Max

      It means var x = z();

    • it’s a handler for several functions as one

  • chintan prajapati

    what es6/7 short hand guide ?

  • long hand :
    // var $return = some object or array or string or int anything.
    if ( $return ) { return true ; }
    else { return false; }

    Shorthand :
    return !! $return;

  • Shaho Awier

    Shorthand for declaring objects if some other value exists

    let json ={ key1: 'value' }
    let var1 = true;
    var1 === true ? json.key2 = 'value2': false

    Now your JSON won’t contain key2 unless var1 is true

  • Closure Compil-ing along with google js styleguide will teach you something, sure thing.
    By the way, how long did it take to create a copy-paste “article”?

  • it’s about shorthands, and not new features of ES6

  • Phani Mulakaluri

    Arrow functions does NOT seem to be working on IE 11. Is it working on safari and Edge?

  • B.Max


  • krkrsoisosisoi

    i don’t understand the arguments.length part. can someone tell me what it means?

  • Heh



  • ParaBolt

    if(string == ‘str1’ || string == ‘str2′ || string==’str3’) => if(/str1|str2|str3/.test(string))

  • Correction for tip #16:
    the `& l t ;` should be `<`

  • Get lodsh (_).

  • oneiroi

    !1 === false , !0 === true ^.^

Get the latest in JavaScript, once a week, for free.