Optimize your JavaScript code using modern shorthand techniques, tips, and tricks
The life of a developer is always learning new things and keeping up with the changes shouldn't be harder than it already is, and my motive is to introduce all the JavaScript best practices such as shorthand and features which we must know as a frontend developer to make our life easier in 2021.
1. If with multiple conditions
We can store multiple values in the array and we can use the array includes method.
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}
2. If true … else Shorthand
This is a greater short cut for when we have if-else conditions that do not contain bigger logics inside. We can simply use the ternary operators to achieve this shorthand.
// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;
console.log(test);
When we have nested conditions we can go this way.
let x = 300,
test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
3. Declaring variables
When we want to declare the two variables which have the common value or common type we can use this shorthand.
//Longhand
let test1;
let test2 = 1;
//Shorthand
let test1, test2 = 1;
4. Null, Undefined, Empty Checks
When we do create new variables sometimes we want to check if the variable we are referencing for its value is not null or undefined. JavaScript does have a really good shorthand to achieve these functions.
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
5. Null Value checks and Assigning Default Value
let test1 = null,
test2 = test1 || '';
console.log("null check", test2); // output will be ""
6. Undefined Value checks and Assigning Default Value
let test1 = undefined,
test2 = test1 || '';
console.log("undefined check", test2); // output will be ""
Normal Value checks
let test1 = 'test',
test2 = test1 || '';
console.log(test2); // output: 'test'
(BONUS: Now we can use ?? operator for topic 4,5 and 6)
Nullish coalescing Operator
The nullish coalescing Operator ?? is returned the right-hand side value if the left-hand side is null or undefined. By default, it will return the left-side value.
const test= null ?? 'default';
console.log(test);
// expected output: "default"const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
Top comments (1)
Good post!