12 Good JavaScript Shorthand Techniques

Written by yuri.pramos | Published 2017/06/18
Tech Story Tags: javascript | es6 | front-end-development

TLDRvia the TL;DR App

Update 1: Due to a lot of polarizing comments (like loved or hated the article) I just want to be clear that shorthand are useful sometimes and sometimes not, depends on which context, don’t take shorthand code as the best of any situation!

I’ve 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.

1. Null, Undefined, Empty Checks Shorthand

When creating new variables sometimes you want to check if the variable you’re referencing for it’s value isn’t null or undefined. I would say this is a very common check for JavaScript coders.

Longhand

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

Shorthand

let variable2 = variable1  || '';

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

//null value examplelet variable1 = null;let variable2 = variable1  || '';console.log(variable2);//output: '' (an empty string)//undefined value examplelet variable1 = undefined;let variable2 = variable1  || '';console.log(variable2);//output: '' (an empty string)//normal value examplelet variable1 = 'hi there';let variable2 = variable1  || '';console.log(variable2);//output: 'hi there'

2. Object Array Notation Shorthand

Longhand

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

Shorthand

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

3. If true … else Shorthand

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

Longhand:

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

Shorthand:

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

let big = (x > 10);

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

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

4. Declaring variables Shorthand

I think this one is the most used abroad the community, even though we know that javascript uses hoist to your variable declaration. It’s a nice pattern declare all the variables at the top and inline.

Longhand:

let x;let y;let z = 3;

Shorthand:

let x, y, z=3;

5. Assignment Operators Shorthand

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

Longhand:

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

Shorthand:

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

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

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

6. RegExp Object Shorthand

Example to avoid using the RegExp object.

Longhand:

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

Shorthand:

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

8. If Presence Shorthand

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

Longhand:

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

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

Longhand:

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

Shorthand:

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

9. Function Variable Arguments Shorthand

Object literal shorthand can take a little getting used to, but seasoned developers usually prefer it over a series of nested functions and variables. You can argue which technique is shorter, but I enjoy using object literal notation as a clean substitute to functions as constructors.

Longhand:

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

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

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

10. charAt() Shorthand

You can use the eval() function to do this but this bracket notation shorthand technique is much cleaner than an evaluation, and you will win the praise of colleagues who once scoffed at your amateur coding abilities!

Longhand:

"myString".charAt(0);

Shorthand:

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

11. Short function calling

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

Longhand:

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

Shorthand:

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

12. Decimal base exponents

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

Longhand:

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

Shorthand:

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

Published by HackerNoon on 2017/06/18