Javascript

Javascript Shorthand Techniques must know

Shorthand techniques are useful when we have to shorten our code length and keep our code base clean and tidy. It also saves some of our coding time.

1. Ternary Operator

We can write if..else statement in single line of code as follows.

Longhand

const a = 3;
let result;
if(a > 5){
    result = 'Greater than 5';
}
else{
    result = 'Less than 5';
}

Keep it short..

const result = a > 5 ? 'Greater than 5':'Less than 5';

We can also nest if statements.

const result = a > 5 ? 'Greater than 5': a < 5 ?'Less than 5':'Equals to 5';

2. Declaring Variables

We define few or many variables as per requirements in the beginning of the functions. Shorthand method can save us lots of time and space when declaring multiple variables as the same time.

Longhand

let a = 1;
let b = 2;
let c;
let d;

In single line?

let a = 1, b = 2, c, d;

3. If Checks

When doing checks for true or false, assignment operators can be omitted.

Longhand

// check if true
if(a === true) {
   // do something
}

// likewise check if false
if(a !== true){
   // do some other things
}

Shorthand

// check if true
if(a) {
   // do something
}

// likewise check if false
if(!a){
   // do some other thing
}
   

4. For Loop

This is really handy in for loops operations

Longhand

const subjects = ['History','Geography','Maths','Science'];

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

Shorthand

for(let subject in subjects)

// OR to access index only
for(let index in subjects)
   
// OR to access keys in objects
const book = {name:'Book 1', price:'$20'}
for (let key in book)
 console.log(key) // output: name, price

5. Short-circuit Evaluation

Assigning a default value to a variable if the intended parameter is null or undefined, we either set the default value to variable first and check the condition to reassign value to the variable. OR we declare a variable, check intended parameter is not null or not undefined and assign value to variable, else assign default value to the variable.

Longhand

let price = 0;
if(book.price){
   price = book.price;
}

// OR
let price;
if(book.price){
   price = book.price;
}
else{
   price = 0;
}

Single liner…

let price = book.price || 0;

6. Decimal Base Exponents

We can write numbers without trailing zeros like, 1e6, which essentially mens 1 followed by 6 zeros (i.e. 1,000,000).

Longhand

for (let a = 0; a < 1000000; a++) {}

Shorthand

for (let a = 0; a < 1e6; a++) {}

// 1e0 = 1
// 1e1 = 10
// 1e2 = 100
// 1e3 = 1000
// 1e4 = 10000
// 1e5 = 100000

7. Object Property

Defining object literals/keys in JS is much easy. It is even more easier the ES6 way. It is useful when variable name is same as the object key.

Longhand

const name = 'Book 1', price = 20;
const book = { name:name, price:price };

In one line..

const book = { name, price };

8. Shorthand Arrow Functions

Defining functions are easy to read and write in their form, but tends to become bit confusing once we start nesting them with other functions.

Longhand

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

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

books.forEach(function(book) {
 console.log(book);
});

Shorthand

greet = name = console.log('Hello', name);

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

books.forEach(book => console.log(book));

9. Implicit Return

Return is a keyword used to return the final result of the function. Arrow function with a single statement will implicitly return the result, for which we have to omit the curly braces ({}) to be able to omit return keyword.

Longhand

function multiply(a,b){
   return a * b;
}

Shorthand

multiply = (a,b) => (
   a * b
)

10. Default Function Parameter Values

We can use if statements to assign default values for the function parameters. ES6 lets us define the default values in the function declaration itself.

Longhand

function area(l, b) {
 if (l === undefined)
   l = 1;
 if (b === undefined)
   b = 1;
 return l * b;
}

Shorthand

area = (l = 1, b = 1) => ( l * b );

area(2,4) // output: 8
area(4) // output: 4

11. String Concatenate

In JS, we use ‘ + ‘ operator to concatenate multiple variables or strings into a single string. It is easy until you have limited number of variables to concatenate. ES6 gives an easy way to do so, no matter how many variables we have to concatenate, by using backticks (`), and ${} to enclose our variables.

Longhand

const message = "Good Morning " + salutation + ' ' + firstname + ' ' + lastname;
const url = 'https://' + host + ':' + port + '/';

Shorthand

const message = `Good Morning ${salutation} ${firstname} ${lastname}`;
const url = `https://${host}:${post}/`;

12. Multi-line String

We usually write multi-line strings in js using concatenate operator ‘ + ‘. We can do it in an easy with backticks.

Longhand

const message = 'Hello \n\t'
+ 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr,\n\t'
+ 'sed diam nonumy eirmod tempor invidunt ut labore et dolore \n\t'
+ 'magna aliquyam erat, sed diam voluptua. At vero eos et accusam et\n\t'
+ 'justo duo dolores et ea rebum. Stet clita kasd gubergren.'

Shorthand

const message = `Hello 
    Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
    sed diam nonumy eirmod tempor invidunt ut labore et dolore 
    magna aliquyam erat, sed diam voluptua. At vero eos et accusam et
    justo duo dolores et ea rebum. Stet clita kasd gubergren.`

13. Array.find

We usually go for for loop if we ever have to find any value from the array of objects. ES6 made it easy with find()

Longhand

const books = [
  {name:'Book 1',price:20},
  {name:'Book 2',price:50}
  {name:'Book 3',price:34}
]

function findBook(price) {
 for(let i = 0; i < books.length; i++) {
   if(books[i].price === price) {
     return books[i];
  }
}
}

Shorthand

book = books.find(book => book.price === 50);
console.log(book); // { name: 'Book 2', price: 50 }

14. Exponent Power

We usually use JS Math for exponent power functions.

Longhand

Math.pow(2,3); //8
Math.pow(3,3); //27
Math.pow(2,6); //64

Shorthand

2**3 // 8
3**3 // 27
2**6 // 64

15. Converting a string to Number

At different point of our projects, we sometimes receive data in String format where we need the data in Numeric format. For such cases, we can perform quick data format conversion.

Longhand

const age = parseInt("24");
const price =  parseFloat("100.03");

Shorthand

const age = +"24"; // converts to int data type
const price =  +"100.03"; // converts to float data type