DEV Community

Heru Hartanto
Heru Hartanto

Posted on • Edited on

8 2

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

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

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more