DEV Community

kalhong90s
kalhong90s

Posted on

20 JavaScript: Shorthand Techniques that will save your time

The shorthand techniques of any programming language help you to write more clean and optimized code. Shorthand techniques improve readability of your code and you can achieve your goal with less coding. Let’s discuss some of the shorthand techniques of JavaScript one by one.

1. Declaring variables

//Longhand 
let x; let y = 20; 

//Shorthand 
let x, y = 20;
Enter fullscreen mode Exit fullscreen mode

2. Assigning values to multiple variables
We can assign values to multiple variables in one line with array destructuring.

//Longhand 
let a, b, c; 
a = 5; 
b = 8; 
c = 12;

//Shorthand 
let [a, b, c] = [5, 8, 12];
Enter fullscreen mode Exit fullscreen mode

3. The Ternary operator
We can save 5 lines of code here with ternary (conditional) operator.

//Longhand 
let number = 26; 
let isEven; 
if(number % 2){
 isEven = true; 
}else{ 
 isEven = false; 
} 
//Shorthand 
let isEven = number % 2 ? true : false;
Enter fullscreen mode Exit fullscreen mode

4. Assigning default value
We can use OR(||)short circuit evaluation to assign a default value to a variable in case the expected value found empty.

//Longhand 
let imagePath; 
let path = getImagePath(); 
if(path !== null && path !== undefined && path !== '') { 
  imagePath = path; 
} else { 
  imagePath = 'default.jpg'; 
} 

//Shorthand 
let imagePath = getImagePath() || 'default.jpg';
Enter fullscreen mode Exit fullscreen mode

5. AND(&&) Short circuit evaluation
If you are calling a function only if a variable is true, then using AND(&&) short circuit you can do it in a single line.

//Longhand 
if (isLoggedin) {
 goToHomepage(); 
} 

//Shorthand 
isLoggedin && goToHomepage();
Enter fullscreen mode Exit fullscreen mode

Here in shorthand technique, if isLoggedin returns true, then only goToHomepage()will execute.

6. Swap two variables
To swap two variables, we often use a third variable. We can swap two variables easily with array destructuring assignment.

let x = 'Hello', y = 55; 

//Longhand 
const temp = x; 
x = y; 
y = temp; 

//Shorthand 
[x, y] = [y, x];
Enter fullscreen mode Exit fullscreen mode

7. Arrow Function

//Longhand 
function add(num1, num2) { 
   return num1 + num2; 
} 

//Shorthand 
const add = (num1, num2) => num1 + num2;
Enter fullscreen mode Exit fullscreen mode

8. Template Literals
We normally use + operator to concatenate string values with variables. With ES6 template literals we can do it in a more simple way.

//Longhand 
console.log('You got a missed call from ' + number + ' at ' + time); 

//Shorthand 
console.log(`You got a missed call from ${number} at ${time}`);
Enter fullscreen mode Exit fullscreen mode

9. 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;
Enter fullscreen mode Exit fullscreen mode
// Shorthand
import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;
Enter fullscreen mode Exit fullscreen mode

You can even assign your own variable names:

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

10. Multiple condition checking
For multiple value matching, we can put all values in array and use indexOf() method.

//Longhand 
if (value === 1 || value === 'one' || value === 2 || value === 'two') { 
// Execute some code 
} 

// Shorthand 
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { 
// Execute some code 
}
Enter fullscreen mode Exit fullscreen mode

11. Object Property Assignment
If the variable name and object key name is same then we can just mention variable name in object literals instead of both key and value. JavaScript will automatically set the key same as variable name and assign the value as variable value.

let firstname = 'Amitav';
let lastname = 'Mishra';


//Longhand 
let obj = {firstname: firstname, lastname: lastname}; 

//Shorthand 
let obj = {firstname, lastname};
Enter fullscreen mode Exit fullscreen mode

12. String into a Number
There are built in methods like parseInt and parseFloat available to convert a string to number. We can also do this by simply providing a unary operator (+) in front of string value.

//Longhand 
let total = parseInt('453'); 
let average = parseFloat('42.6'); 

//Shorthand 
let total = +'453'; 
let average = +'42.6';
Enter fullscreen mode Exit fullscreen mode

13. Repeat a string for multiple times
To repeat a string for a specified number of time you can use a for loop. But using the repeat() method we can do it in a single line.

//Longhand 
let str = ''; 
for(let i = 0; i < 5; i ++) { 
  str += 'Hello '; 
} 
console.log(str); // Hello Hello Hello Hello Hello 

// Shorthand 
'Hello '.repeat(5);
Enter fullscreen mode Exit fullscreen mode

Tip: Want to apologize to someone by sending 100 times “sorry”? Try it with repeat() method. If you want to repeat each string in a new line, then add \n to the string.

'sorry\n'.repeat(100);
Enter fullscreen mode Exit fullscreen mode

14. Exponent Power
We can use Math.pow() method to find the power of a number. There is a shorter syntax to do it with double asterik (**).

//Longhand 
const power = Math.pow(4, 3); // 64 

// Shorthand 
const power = 4**3; // 64
Enter fullscreen mode Exit fullscreen mode

15. Double NOT bitwise operator (~~)
The double NOT bitwise operator is a substitute for Math.floor() method.

//Longhand 
const floor = Math.floor(6.8); // 6 

// Shorthand 
const floor = ~~6.8; // 6
Enter fullscreen mode Exit fullscreen mode

16. Find max and min number in array
We can use for loop to loop through each value of array and find the max or min value. We can also use the Array.reduce() method to find the max and min number in array.But using spread operator we can do it in a single line.

// Shorthand 
const arr = [2, 8, 15, 4]; 
Math.max(...arr); // 15 
Math.min(...arr); // 2
Enter fullscreen mode Exit fullscreen mode

17. For loop
To loop through an array we normally use the traditional for loop. We can make use of the for...of loop to iterate through arrays. To access the index of each value we can use for...in loop.

let arr = [10, 20, 30, 40]; 

//Longhand 
for (let i = 0; i < arr.length; i++) { 
  console.log(arr[i]); 
} 
//Shorthand 
//for of loop 
for (const val of arr) { 
  console.log(val); 
} 
//for in loop 
for (const index in arr) { 
  console.log(arr[index]); 
}
We can also loop through object properties using for...in loop.

let obj = {x: 20, y: 50}; 
for (const key in obj) { 
  console.log(obj[key]); 
}
Enter fullscreen mode Exit fullscreen mode

18. Merging of arrays

let arr1 = [20, 30]; 

//Longhand 
let arr2 = arr1.concat([60, 80]); 
// [20, 30, 60, 80] 

//Shorthand 
let arr2 = [...arr1, 60, 80]; 
// [20, 30, 60, 80]
Enter fullscreen mode Exit fullscreen mode

19. Deep cloning of multi-level object
To deep clone a multi-level object, we can iterate through each property and check if the current property contains an object. If yes, then do a recursive call to the same function by passing the current property value (i.e. the nested object).We can also do it by using JSON.stringify() and JSON.parse() in a single line.

let obj = {x: 20, y: {z: 30}}; 

//Longhand 
const makeDeepClone = (obj) => { 
  let newObject = {}; 
  Object.keys(obj).map(key => { 
    if(typeof obj[key] === 'object'){ 
      newObject[key] = makeDeepClone(obj[key]); 
    } else { 
      newObject[key] = obj[key]; 
    } 
  }); 
 return newObject; 
} 
const cloneObj = makeDeepClone(obj); 

//Shorthand 
const cloneObj = JSON.parse(JSON.stringify(obj));
Enter fullscreen mode Exit fullscreen mode

20. Get character from string

let str = 'jscurious.com'; 

//Longhand 
str.charAt(2); // c 

//Shorthand 
str[2]; // c
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

Top comments (0)