Home > database >  How to avoid writing multiple && operators in if statement?
How to avoid writing multiple && operators in if statement?

Time:10-27

I have a if statement where I have multiple && operators.

if (firstname.value !=="" && lastname.value !=="" && phone.value !=="" && emailverified.value ==="1" && personcheck.checked === false){
//something//
}else{
//something else//
}

How can I put these into a single line and insert it in if statement so I can avoid multiple operators? Like this?


if (condition){
//something//
} else{
//something else//
}```

CodePudding user response:

create one more function called isValid

function isValid() {
return firstname.value !=="" && lastname.value !=="" && phone.value !=="" && emailverified.value ==="1" && personcheck.checked === false;
}
if (isValid()){
//something//
} else{
//something else//
}```

CodePudding user response:

Well, you can group the ones comparing similar things to one group and shorten the other ones, something like:

if ([firstname, lastname, phone].every(({ value }) => value.length)
    && emailverified.value == 1 && !personcheck.checked) {
  // ...
} else {
  // ...
}

CodePudding user response:

const condition = firstname.value !=="" && lastname.value !=="" && phone.value !=="" && emailverified.value ==="1" && personcheck.checked === false

if (condition){
//something//
} else{
//something else//
}```

CodePudding user response:

Perhaps give nested "if" statements a try.

  • Related