JavaScript
Article
By Michael Wanyoike

19+ JavaScript Shorthand Coding Techniques

By Michael Wanyoike

improve-your-javascript

This really is a must read for any JavaScript-based developer. I have written this article 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 is going on I have included the longhand versions to give some coding perspective.

June 14th, 2017: This article was updated to add new shorthand tips based on ES6. If you want to learn more about the changes in ES6, sign up for SitePoint Premium and check out our screencast A Look into ES6

1. The Ternary Operator

This is a great code saver when you want to write an if..else statement in just one line.

Longhand:

const x = 20;
let answer;
if (x > 10) {
    answer = 'is greater';
} else {
    answer = 'is lesser';
}

Shorthand:

const answer = x > 10 ? 'is greater' : 'is lesser';

You can also nest your if statement like this:

const big = x > 10 ? " greater 10" : x 

2. Short-circuit Evaluation Shorthand

When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined or empty. You can either write a long if statement with multiple conditionals, or use a short-circuit evaluation.

Longhand:

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

Shorthand:

const variable2 = variable1  || 'new';

Don’t believe me? Test it yourself (paste the following code in es6console):

let variable1;
let variable2 = variable1  || '';
console.log(variable2 === ''); // prints true

variable1 = 'foo';
variable2 = variable1  || '';
console.log(variable2); // prints foo

3. Declaring Variables Shorthand

It is good practice to declare your 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:

let x;
let y;
let z = 3;

Shorthand:

let x, y, z=3;

4. If Presence Shorthand

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

Longhand:

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

Note: these two examples are not exactly equal, as the shorthand check will pass as long as likeJavaScript is a truthy value.

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

Longhand:

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

Shorthand:

let a;
if ( !a ) {
// do something...
}

5. JavaScript for Loop Shorthand

This little tip is really useful if you want plain JavaScript and not rely on external libraries such as jQuery or lodash.

Longhand:

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

Shorthand:

for (let index 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

6. Short-circuit Evaluation

Instead of writing six lines of code to assign a default value if the intended parameter is null or undefined, we can simply use a short-circuit logical operator and accomplish the same thing with just one line of code.

Longhand:

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = 'localhost';
}

Shorthand:

const dbHost = process.env.DB_HOST || 'localhost';

7. Decimal base exponents

You may have seen this one around. It’s essentially a fancy way to write numbers without the trailing zeros. For example, 1e7 essentially means 1 followed by 7 zeros. It represents a decimal base (which JavaScript interprets as a float type) equal to 10,000,000.

Longhand:

for (let i = 0; i < 10000; i++) {}

Shorthand:

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

// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

8. Object Property Shorthand

Defining object literals in JavaScript makes life much easier. ES6 provides an even easier way of assigning properties to objects. If the property name is the same as the key name, you can take advantage of the shorthand notation.

Longhand:

const obj = { x:x, y:y };

Shorthand:

const obj = { x, y };

9. Arrow Functions Shorthand

Classical functions are easy to read and write in their plain form, but they do tend to become a bit verbose and confusing once you start nesting them in other function calls.

Longhand:

function sayHello(name) {
  console.log('Hello', name);
}

setTimeout(function() {
  console.log('Loaded')
}, 2000);

list.forEach(function(item) {
  console.log(item);
});

Shorthand:

sayHello = name => console.log('Hello', name);

setTimeout(() => console.log('Loaded'), 2000);

list.forEach(item => console.log(item));

10. Implicit Return Shorthand

Return is a keyword we use often to return the final result of a function. An arrow functions with a single statement will implicitly return the result its evaluation (the function must omit the braces ({}) in order to omit the return keyword).

To return a multi-line statement (such as an object literal), it’s necessary to use () instead of {} to wrap your function body. This ensures the code is evaluated as a single statement.

Longhand:

function calcCircumference(diameter) {
  return Math.PI * diameter
}

Shorthand:

calcCircumference = diameter => (
  Math.PI * diameter;
)
--ADVERTISEMENT--

11. Default Parameter Values

You can use the if statement to define default values for function parameters. In ES6, you can define the default values in the function declaration itself.

Longhand:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}

Shorthand:

volume = (l, w = 3, h = 4 ) => (l * w * h);

volume(2) //output: 24

12. Template Literals

Aren’t you tired of using ' + ' to concatenate multiple variables into a string? Isn’t there a much easier way of doing this? If you are able to use ES6, then you are in luck. All you need to do is use is the backtick, and ${} to enclose your variables.

Longhand:

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

Shorthand:

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;

13. Destructuring Assignment Shorthand

If you are working with any popular web framework, there are high chances you will be using arrays or data in the form of object literals to pass information between components and APIs. Once the data object reaches a component, you’ll need to unpack it.

Longhand:

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

Shorthand:

import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;

You can even assign your own variable names:

const { store, form, loading, errors, entity:contact } = this.props;

14. Multi-line String Shorthand

If you have ever found yourself in need of writing multi-line strings in code, this is how you would write it:

Longhand:

const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
    + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
    + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
    + 'veniam, quis nostrud exercitation ullamco laboris\n\t'
    + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
    + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'

But there is an easier way. Just use backticks.

Shorthand:

const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`

15. Spread Operator Shorthand

The spread operator, introduced in ES6, has several use cases that make JavaScript code more efficient and fun to use. It can be used to replace certain array functions. The spread operator is simply a series of three dots.

Longhand

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

Shorthand:

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

Unlike the concat() function, you can use the spread operator to insert an array anywhere inside another array.

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

You can also combine the spread operator with ES6 destructuring notation:

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

16. Mandatory Parameter Shorthand

By default, JavaScript will set function parameters to undefined if they are not passed a value. Some other languages will throw a warning or error. To enforce parameter assignment, you can use an if statement to throw an error if undefined, or you can take advantage of the ‘Mandatory parameter shorthand’.

Longhand:

function foo(bar) {
  if(bar === undefined) {
    throw new Error('Missing parameter!');
  }
  return bar;
}

Shorthand:

mandatory = () => {
  throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
  return bar;
}

17. Array.find Shorthand

If you have ever been tasked with writing a find function in plain JavaScript, you would probably have used a for loop. In ES6, a new array function named find() was introduced.

Longhand:

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
  }
}

Shorthand:

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18. Object [key] Shorthand

Did you know that Foo.bar can also be written as Foo['bar']? At first, there doesn’t seem to be a reason why you should write it like that. However, this notation gives you the building block for writing re-usable code.

Consider this simplified example of a validation function:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:'Bruce',last:'Wayne'})); // true

This function does its job perfectly. However, consider a scenario where you have very many forms where you need to apply the validation but with different fields and rules. Wouldn’t it be nice to build a generic validation function that can be configured at runtime?

Shorthand:

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}


console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

Now we have a validate function we can reuse in all forms without needing to write a custom validation function for each.

19. Double Bitwise NOT Shorthand

Bitwise operators are one of those features you learn about in beginner JavaScript tutorials and you never get to implement them anywhere. Besides, who wants to work with ones and zeroes if you are not dealing with binary?

There is, however, a very practical use case for the Double Bitwise NOT operator. You can use it as a replacement for Math.floor(). The advantage of the Double Bitwise NOT operator is that it performs the same operation much faster. You can read more about Bitwise operators here.

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!

  • 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:
    if(something==True){
    something=False
    }else{
    something=True
    }

    ShortHand:
    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’
    };
    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”])

    • 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.
    Cheers.
    – 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) {
        x();
    } else {
        y();
    }

    Shorthand:

    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() http://jsperf.com/foreach-vs-jquery-each/9

    • 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

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

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

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

    }

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

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

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

      • 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.
      Thanks,
      Sam

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

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

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

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

      outputs
      0
      1
      ‘foo’

  • Nice, thanks John.

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

    • David Turner

      Quite right, this author is clearly no expert.

    • Gaby

      Agreed.
      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’;
      skillSet.length;
      skillSet[0]

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

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

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

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

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

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

        • ddddd

          or even shorter, just use “value = !value”. Doesn’t need double “!”.

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

    • 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 = Date.now();
      arguments[i]();
      total += Date.now()-start;
      }
      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

    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.

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

    if(x){
    y()
    }

    Shorthand:
    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, [].slice.call(arguments, 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.

    • Nikola

      Also working nicely with JSX in react ;)

  • 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

    Long:
    parseInt(“1337″)

    Short:
    +”1337”

    will both return integer
    1337

    • 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

    Longhand:
    $.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 = Array.prototype.slice.call(arguments);

    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.call(arguments);

    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 http://jsperf.com/switch-case-shorthand

  • borto matheo

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

    Shorthand:

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

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

    ——-

    Longhand:

    for(i=7;i>0;i–)

    Shorthand:

    for(i=8;–i;)

    ——-
    Longhand while(1){}
    Shorthand:for(;;){}

    ok lol for 1 letter

    ——–

    the example with switch is no optimal here my way :

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

    }

    Shorthand

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

    Longhand :

    if(a){

    b=5;

    }

    b = a && 5;

    warning b == false if not a,

    but you can use || for else if

    —–
    Longhand :

    (function(){alert()})()

    shortand:

    ~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

    Longhand:

    var c;

    a1()

    c = a

    if(!a){

    b1()

    c=b

    }

    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

    —-

    parseInt(“10.5″);

    +”10.5”

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

    i=8;

    do{

    cond = myFunc(i);

    }while(i–,cond)


    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

    Longhand:
    var c=a,a=b,b=a;

    Shorthand:
    a=[b,b=a][0];

    • Simeon

      You can also use it to turn code into a 1 liner
      a=[b,doStuff(),doMoreStuff(),doSomeMoreStuff(),…][0]

  • jkk

    Instead of
    var x = function(s){ alert(s); }
    or
    function x(s){ alert(s); }
    use
    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()
    Longhand:

    Math.floor(4.9); // 4

    Shorthand:

    4.9 | 0; // 4

    ————————————-
    XOR Swap
    Longhand:

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

    Shorthand:

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

    ————————————-
    Integer division by the power of two
    Longhand:

    Math.floor(x/2);

    Shorthand:

    x>>1;

    ————————————-
    Check if variables have the same sign
    Longhand:

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

    Shorthand:

    (x ^ y) >= 0;

    ————————————-
    Toggle between two values
    Longhand:

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

    Shorthand:

    x = a ^ b ^ x;

    …and more

    • B.Max

      Nice.

  • 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

    Yes.

  • krkrsoisosisoi

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

  • Heh

    Longhand:
    if(!x){
    y();
    }

    Shorthand:
    x||y();

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

  • Joan Miquel Torres Rigo

    Shorter switch() version (Tip n. 14):

    ({
    1: doX,
    2: doY,
    3: doN,
    }[something]
    || (x=>x))()

  • Limo Sadalla

    If (cow != null) can be writted as

    if (!!cow)

  • Claudio Bonifazi

    I’m sorry, isn’t #4 wrong?
    if( v ) isn’t equal to if( v === true ), but to if( v == true || v > 0 || v.length > 0 )

  • Stian Jensen

    Number 5 is a bit confusing, because with a for-in loop, img is going to be the index of the array and not the value. So I’d suggest changing either the variable name to i to indicate it’s the index, or change the loop to a for-of loop which will give you the value directly instead.

    • You are right #5 is confusing. Should have used ‘index’ for arrays, and ‘key’ for associative arrays. Will update the article to reflect that

  • Daniel

    4.- “if (likeJavaScript === true)” is not the longhand of “if (likeJavascript)”

  • daniel morales

    Long:
    var today = new Date();
    today.getTime();
    // 1497532074540

    Short
    var today = new Date();
    today++;
    // 1497532074540

    • Milan Holý

      or just var today = +new Date();

    • Thank you Daniel for your contribution

  • “Did you know that Foo.bar can also be written as Foo[bar]?”

    You mean `Foo[‘bar’]` instead, because `bar` is `undefined` ;)

    • Thanks for that correction, meant to say `Foo[‘bar’]`. However, Foo[bar] can also work if i had declared bar as a variable

      • Yes but in that case bar is an undefined variable, and then schema[field] is ok

  • Steve Griffith

    Correction for #12. In the long hand version there should be no quotation marks around ‘port’.

    • Are you sure?

      Try this example

      “`
      const host = ‘localhost’;
      const port = 3306;
      const database = ‘testdb’;
      const db = ‘http://’ + host + ‘:’ + port + ‘/’ + database;

      console.log(db); // http://localhost:3306/testdb
      “`

      • Steve Griffith

        Your example is fine. The one above had single quotes around the port variable.

  • Steve Griffith

    Correction for #18 shorthand. When the function validate is being called you need to pass in the schema as the first argument OR you should remove the first parameter “schema” from the function definition and just be using the global constant called schema. Currently, you are creating a new local variable called “schema” and you are passing your data to be validated into that variable.

    • This code I’ve used is a simplified example of how you can use Object[‘key’] shorthand. The assumption here is that a developer needs to validate multiple domain classes by reusing the same validation function. The ‘schema’ is just a bunch of validation rules that belongs to a specific domain class. Hence you need to create a schema variable for each domain class.

  • Iterating an array using for..in is plain wrong, if the collection has a modified prototype, it will also show that proto key, ES6 provides the for..of loop instead:

    for (let item of items) console.log(item)

    A few shorthands I know
    ========================
    Longhand:
    “ABC”.split(”)
    Shorthand
    […”ABC”]

    This isn’t really a shorthand but a tip in functional programming
    when you have to pass a callback function of N arity (arity = the number of parameters a function takes), instead of creating a annonymous function that only seeds the received N arguments from the callee, you can do this:

    [65, 66, 67].map(code => String.fromCharCode(code)).join(”) // “ABC”
    you can instead do
    [65, 66, 67.map(String.fromCharCode).join(”) // “ABC”

    Coercing strings to numbers:

    Longhands:
    parseInt(numberStr, radix)
    Number(numberStr)
    Shorthands:
    +numberStr
    `0b${binary}` // where binary = “101” > yields 5
    `0x${hex}` // where hex = “FF” > yields 255

    Creating a matrix filled with something:
    M = 3
    N = 4
    something = 0

    Array(M).fill(Array(N).fill(something))
    // yields [[0,0,0,0], [0,0,0,0], [0,0,0,0]]

    Creating a range (inclusive on both extremes):
    […Array(max – min + 1)].map((_, i) => i + min) // where min = 3, max = 6
    // yields [3,4,5,6]

    Also, tip, if you’re required to sum a range, use the properties of the summatory in math instead of solving it with iteration, it’d take O(1) instead of O(N). Overall, if something cal be solved with math, use math.

    Experimental ES6 shorthand for object shallow cloning
    const a = { prop1: ‘a’, prop2: ‘b’ }
    const b = { prop3: ‘c’, prop3: ‘d’ }
    const aPlusB = { …a, …b } // it’s shorthand for Object.assign, it copies whatever’s in a and b in that order into a brand new object literal, if there’s key collision, the most recent version is updated; this is a common task in Redux for updating the state.

    Experimental ES6 shorthand for function bind
    context::function(arguments) // transforms into function.bind(context)(arguments)
    You can google “babel transform function bind” for more info

    • Thanks for your contribution Luis. #5 will soon be updated with the for..of loop code.

  • very helpful, thanks Michael.

  • Andrew Luca


    const x = 20;
    let big;

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

    // same
    const big = x > 10 ? true : false;

    // same
    const big = x > 10;

    • You are right. This should make more sense to readers:

      const result = x > 10 ? ‘is greater’ : ‘is smaller’;

  • Very nice list. Thank you for your contribution xem

  • wunch

    Could you more clearly identify, perhaps with a tag or something on each item, which of these are ES6-specific? Or even put the ES6 ones into a separate section? For example, I believe arrow functions are an ES6 thing, but there is currently no indication in the article of that.

  • Gary Herd

    Good stuff, thanks Michael!

  • jackdurango

    just be careful with shorthand – it can make things a bit unreadable (sometimes) and then later, when you go back over your code, it can take a bit to realize what you were doing

  • Embrace boolean expressions! Don’t write
    const big = x > 10 ? true : false;
    Instead write
    const big = x > 10;

  • Baxter

    It’s probably worth mentioning that just because you can write something short hand doesn’t mean that you should. Code eligibility is more important than code length.

  • Rahul Das

    Shorthand for shorthand:
    const big = x > 10? true : false;

    we can just use:
    const big = x > 10;

  • Be aware that the shorthand for #9 is not strictly equivalent to the longhand “function” form. The longhand creates a new “this” context, while shorthand, arrow functions retain the definition of “this” from its surrounding context.

  • Yusuf Akhsan Hidayat

    so helpful, i have been accustomed to using shorthand since the end of this year

  • Mariusz Maroń

    I would suggest: 2 ** 3 instead of Math.pow(2,3) ?

  • Yusuf Akhsan Hidayat

    what about if in one line

    long hand
    if(status === ‘ready’)
    {
    /** do action */
    }

    short hand
    if(status === ‘ready’) /** do action */

  • The first shorthand of

    const big = x > 10 ? true : false;

    can really just be a short-shorthand, as in:

    const big = x > 10;

    • nnnnnn321

      The author should’ve demonstrated the ternary operator with an assignment of non-Boolean values, where it makes sense.

  • nnnnnn321

    8. “If the property name is the same as the key name, you can take advantage of the shorthand notation.”

    No. If the property value is coming from a variable that has the same name as the object property then you can use this shorthand notation. (The original wording that I quoted makes no sense, because “value” isn’t mentioned at all, and in the context of objects “key” means “property name”.)

  • Артем Иванов

    #18
    const validate = (schema, values) =>
    !Object.keys(schema)
    .some(field=>schema[field].required && !values[field]);

  • My five cents of caution regarding performance on this tip: 15. Spread Operator Shorthand

    […array] is much slower than array.slice() (Test it)

  • Igor Ermakov

    let str = ‘Lorem ipsum’
    if (~str.indexOf(‘ipsum’)) {
    // found
    }

  • Nouran Mahmoud

    I’ve a comment on point (2) this shorthand will be useful until you use a variable which has a boolean value.. this shorthand won’t work fine with you, because if variable1 is false it will not be considered as a value and it will store the right side option .. consider the following example:-

    “`
    const variable1 = false;
    const variable2 = variable1 || ‘new’
    variable2 // will be ‘new’ however variable1 has a value
    “`

  • Kaew Pj

    function calcBmi({ weight: w, height: h, max = 25, callback }){
    var bmi = w / Math.pow(h, 2);
    if( bmi > max ){
    console.log(“You’re overweight”);
    }

    if(callback && callback instanceof Function){
    callback(bmi);
    }
    }

    let options = {
    weight: 90,
    height: 185,
    max: 0.0001,
    callback(result){
    console.log(result);
    }
    }

  • sdeering

    Michael Wanyoike I wrote this post in 2011. How have you suddenly claimed it? Not cool man.

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