Always positive
It's need extra effort to understanding logic in negative condition, avoid it as you can
// โ Don't
function isUserNotVerified(){
}
if(!userVerified){
}
// โ
Do
function isUserVerified(){
}
if(userVerified){
}
Use Shorthands if possible
Shorthands make your code use less line and easier to read
// โ Don't
if(isActive ==null){
}
if(firstname !== null || firstname !=='' || firstname !== undefined){
}
const isUserValid = user.isVerified() && user.isActive() ? true : false;
// โ
Do
if(isActive) {
}
if(!!firstname){
}
const isUserValid = user.isVerified() && user.isActive()
Object literals over Switch statements
// โ Don't
const getStatus = (status) => {
switch (status) {
case "success":
return "green";
case "failure":
return "red";
case "warning":
return "yellow";
case "loading":
default:
return "blue";
}
};
// โ
Do
const statusColors = {
success: "green",
failure: "red",
warning: "yellow",
loading: "blue",
};
const getStatus = (status) => statusColors[status] || statusColors.loading;
Use optional chaining
Remember that optional chaining is not working with IE browser yet, see here
const alice = {
name:'Alice',
cat:{
name:'Nala'
}
}
// โ Don't
const cat = (alice && alice.cat && alice.cat.name) || 'N/A';
// โ
Do
const cat = alice?.cat?.name ?? 'N/A';
Top comments (3)
For shorthands like if(!!something), why cant we just do if (something)???
Yes you could, the only difference is !!something will return boolean