TIL some ways to refactor your code
POSTED ON:
TAGS: javascript cleancode refactor
Shorthand tricks:
Shorthand for multiple OR (||
) conditions. #
// INSTEAD OF THIS:
if (fruit === 'apple' || fruit === 'orange' || fruit === 'banana' || fruit ==='grapes') {
//code
}
// DO THIS:
if (['apple', 'orange', 'banana', 'grapes'].includes(fruit)) {
//code
}
Shorthand for multiple AND conditions. #
// INSTEAD OF THIS:
if(obj && obj.address && obj.address.postalCode) {
console.log(obj.address.postalCode)
}
// DO THIS: Use optional chaining
console.log(obj?.address?.postalCode);
Shorthand to check for null/undefined/empty or to set a default value #
// INSTEAD OF THIS:
if (first !== null || first !== undefined || first !== '') {
let second = first;
}
// DO THIS:
const second = first || '';
Shorthand for replacing switch cases #
// INSTEAD OF THIS
switch (number) {
case 1:
return 'one';
case 2:
return 'two';
default:
return;
}
// DO THIS:
const data = {
1: 'one',
2: 'two'
};
data[num]
Shorthand for calling functions conditionally #
// INSTEAD OF THIS:
function area() {
console.log('area');
}
function volume() {
console.log('volume');
}
if( type === 'square' ) {
area();
} else {
volume();
}
// DO THIS:
(type === 'square' ? area : volume)()
Via
https://javascript.plainenglish.io/stop-writing-javascript-like-this-a7fafbe451a5
Related TILs
Tagged: javascript