LazioTibijczyk
LazioTibijczyk

Reputation: 1957

if statement condition in an if statement condition

I'm struggling with an if statement where I want to add another condition if user is admin on top of whether vm.model.purchaseDate is not empty like so

Need some pseudo code to explain it

if(vm.model.purchaseDate && (vm.user.admin then also if(anotherCondition))) {
   //do something1
   //do something2
   //do something3
   //do something4
} else {
   //do something else
}

So if vm.model.purchaseDate is defined and user is NOT vm.user.admin then ignore anotherCondition. If user is vm.user.admin then also check anotherCondition.

I don't want to end up writing lots of ifs when my //do something code is pretty long. Trying to avoid this

if(vm.model.purchaseDate) {
   if(vm.user.admin) {
      if(anotherCondition) {
         //do something1
         //do something2
         //do something3
         //do something4
       }
   } else {
      //do something1
      //do something2
      //do something3
      //do something4
   }
} else {
   //do something else
}

Upvotes: 2

Views: 144

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

Use OR (||) with !vm.user.admin and anotherCondition:

if(vm.model.purchaseDate && (!vm.user.admin || anotherCondition)) {
   //do something1
   //do something2
   //do something3
   //do something4
} else {
   //do something else
}

That way:

  • If the user is not an admin, !vm.user.admin is true and the || takes true as its result
  • If the user is an admin, !vm.user.admin is false and so || takes the result of evaluating anotherCondition as its result

Upvotes: 6

Related Questions