1. Declaring variables

let x;
let y = 20;
​
//Shorthand
let x, y = 20;

2. Assigning values to multiple variables

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

let a, b, c;
​
a = 5;
b = 8;
c = 12;
​
//Shorthand
let [a, b, c] = [5, 8, 12];

3. The Ternary operator

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

let marks = 26; 
let result; 
if(marks >= 30){
   result = 'Pass'; 
}else{ 
   result = 'Fail'; 
} 
​
//Shorthand 
let result = marks >= 30 ? 'Pass' : 'Fail';

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.

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

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.

if (isLoggedin) {
    goToHomepage();
 }
​
//Shorthand
isLoggedin && goToHomepage();

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

Read the original post in jscurious.com

#javascript #shorthand #web-development #typescript

20 JavaScript Shorthand Techniques that will save your time - JS Curious
2.15 GEEK