DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Heru Hartanto
Heru Hartanto

Posted on • Updated on

Clean your condition 🧼

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){

}

Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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';

Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
mikenatsu profile image
MikeNatsu

For shorthands like if(!!something), why cant we just do if (something)???

Collapse
 
elukuro profile image
Heru Hartanto Author

Yes you could, the only difference is !!something will return boolean

Collapse
 
jiko profile image
Jiko
const getStatus = (status = 'loading') => statusColors?.[status] ?? statusColors.loading;
Enter fullscreen mode Exit fullscreen mode

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!