Home > database >  How to double check inside if without writing the same thing twice?
How to double check inside if without writing the same thing twice?

Time:10-19

Is there a way in javascript (or typescript) to avoid re-writing the same object twice inside an if statement condition?

Something like this:

if (A != null || A != B) {
 // do something here
}

// something in the form of this:
if (A != null || != B) { // avoid re-writing "A" here
// do something here
}

Anyone has any suggesgtion or even other questions related to this one?

CodePudding user response:

You could do :

if([B, null].includes(A)) {
   // ...
}

CodePudding user response:

There's no built-in shortcut in if conditions. If in reality A is a cumbersome expression that you want to avoid rewriting, the usual solution would be a temporary variable:

if ( (t=A) != null || t != B ) {
  • Related