Skip to content
Advertisement

Repeated if else blocks

I have an if else construction that will sound absurd to you. Actually, I wrote a basic version of my real code so as not to prolong it. Is there anyone who can rationalize it?

let someThink
let someWhere

if(someThink === true){  
      // get someData in a database and after
      if( someData > 5 ){

             if(someWhere === true){       
                   // get someData2 in a database and after
                  if( someData2 > 3 ){
                    console.log("Go to plans page")
                  } else {
                    console.log("Update data")
                  }       
            } else {
              console.log("Go to plans page")
            }

      } else {
        console.log("Update data")
      }
  
} else if (someWhere === true){
    // get someData2 in a database and after
    if( someData2 > 3 ){
      console.log("Go to plans page")
    } else {
      console.log("Update data")
    }       
  
} else {
  console.log("Go to plans page")
}

Advertisement

Answer

You can use some early returns after finding a case for updating the data:

let someThink
let someWhere

if (someThink) {  
  // get someData in a database and after
  if (someData <= 5) {
    console.log("Update data")
    return;
  }
}

if (someWhere) {
  // get someData2 in a database and after
  if (someData2 <= 3) {
    console.log("Update data")
    return;
  }
}

console.log("Go to plans page");

You can avoid the early returns by putting the data fetching stuff in some helper function instead of inside the decision logic:

let someThink
let someWhere

if (someThink && getSomeData() <= 5
 || someWhere && getSomeData2() <= 3
) {
  console.log("Update data")
} else {
  console.log("Go to plans page");
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement