devludo
devludo

Reputation: 123

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

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?

Upvotes: 0

Views: 67

Answers (2)

Matthieu Riegler
Matthieu Riegler

Reputation: 55866

You could do :

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

Upvotes: 3

Mark Reed
Mark Reed

Reputation: 95375

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 ) {

Upvotes: 0

Related Questions