Hi Everyone,
Today i am going to tell about some js clean code tips based on code readablity not on performance
1) No continuous object properties assign:
let obj = {};
obj.a = '1';
obj.b = '2';
We can write the above code as
Object.assign(obj, { a: '1', b: '2' });
2) Use object destructuring in function arguments:
function print(obj) {
console.log(obj.a);
}
We can write the above code as
function print({ a }) {
console.log(a);
}
3) No unneeded ternary:
let a = b === 10 ? true : false;
let c = d ? true : false;
We can write the above code as
let a = b === 10
let c = !!d
lint rule is https://eslint.org/docs/rules/no-unneeded-ternary
4) No repeated if check:
if(cond1) {
if(cond2) {
// do something
}
}
We can write the above code as
if(cond1 && cond2) {
// do something
}
5) No unneeded boolean return:
function getBoolean() {
if(cond) {
return true;
}
return false;
}
We can write the above code as
function getBoolean() {
return cond;
}
6) Converge object destructuring:
let { prop1 } = obj;
let { prop2 } = obj;
We can write the above code as
let { prop1, prop2 } = obj;
7) No Duplicate Imports:
import { a } from 'filepath';
import { b } from 'filepath';
We can write the above code as
import { a, b } from 'filepath';
lint rule is https://eslint.org/docs/rules/no-duplicate-imports
I hope you enjoyed this post. Thanks for reading.
Source documentation is https://github.com/airbnb/javascript
Top comments (0)