Shorthand in JavaScript

In this article, we look at different shorthand operators and techniques and understand how they save time and code.

A shorthand operator is a shorter way of expressing something that is already available in the Java programming language which leads to lesser lines of code. But, using shorthand operators & techniques reduces the code readability.

Table of Contents

+= operator

This is used for adding two values. Let us first look at the long-hand format using an example and then use the shorthand alternative.

Longhand:

let a = 12;
Let b = 10;
a=a+b;
console.log(a);
//Output: 22


Shorthand:

let a = 12;
Let b = 10;
a+=b;
console.log(a);
//Output: 22


In the above example, we used x += y instead of using x = x + y. Although both of these do the same exact thing which is to assign the sum of x & y to x.

Other Shorthand operators

x = x + y   ->   x += y 
x = x - y    ->    x -= y 
x = x * y    ->    x *= y 
x = x / y    ->   x /= y 
x = x % y    ->    x %= y 


Ternary Operator

Using this operator, we could write the if..else statement in a single line. Let us look at both longhand and shorthand versions.

Longhand:

const a = 30;
let b;

if (a % 2 == 0) {
    b = "Even";
} else {
    b =  "Odd";
}
console.log(b);
//Output: Even


Shorthand:

const b = a % 2 ==  ? "Even" : "Odd";
console.log(b);
//Output: Even


Shorthand variable declaration

Using the below shorthand technique, we could declare multiple variables in a single line. Let us take a look at the longhand and shorthand versions with an example.

Longhand:
let a;
let b;
let c = 100;


Shorthand:
let a, b, c=100;


If Presence

Longhand:
if(xyz == true);


Shorthand
if(xyz == false);


Another instance:
Longhand:
let xyz;
if ( xyz !== true ) {
console.log(Hello world);
}


Shorthand:
let a;
if ( !a ) {
console.log(Hello world);
}