let x;
let y = 20;
//Shorthand
let x, y = 20;
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];
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';
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';
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