#need help in simplifying bunch of conditions

1 messages · Page 1 of 1 (latest)

verbal tinsel
#

hi, I'm trying to write a condition which involves multiple checks step by step , can anyone help me simplifying my code , i tired to use ternary operations but failed so i made them a nested condition

 if (this.remark.valid) { 
      if (this.remark.value.id == 5) {  //only if remark is valid then this should be checked
        if (this.other_reasons.valid) { //only if remark id is 5 then this should be checked
          console.log('valid other reason');
        }
      } else { // if remark id not equal to 5 
        console.log('valid', this.remark.value.id, this.other_reasons.valid);
      }
      this.dialogRef.close();
    }
shrewd abyss
#

there are many way you can optimize your code. The first think I like to do, is to check for false condition and then return:
this doesn't make you code shorter, but it's less indented and easier to read:

if (!this.remark.valid) {
  return;
}
if (this.remark.value.id == 5) {  //only if remark is valid then this should be checked
  if (this.other_reasons.valid) { //only if remark id is 5 then this should be checked
    console.log('valid other reason');
  }
} else { // if remark id not equal to 5 
  console.log('valid', this.remark.value.id, this.other_reasons.valid);
}
this.dialogRef.close();

In this case it doesn't improve the code much, but in many other cases it's good

verbal tinsel
shrewd abyss
#

I think you can do it like this, but it's not very readable:

if (!this.remark.valid) {
  return;
}
this.remark.value.id == 5 ? (this.other_reasons.valid ? console.log('valid other reason' : null) : console.log('valid', this.remark.value.id, this.other_reasons.valid);
this.dialogRef.close();
#

another approach:

if (!this.remark.valid) {
  return;
}
if (this.remark.value.id !== 5){
  console.log('valid', this.remark.value.id, this.other_reasons.valid);
  this.dialogRef.close();
  return;
}
if (this.other_reasons.valid) {
  console.log('valid other reason');
}
this.dialogRef.close();
#

the goal is to make the code readable, not as short as possible

verbal tinsel