0

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?

devludo
  • 93
  • 10
  • 4
    How can `A` equal `B` if it is null? – mousetail Oct 19 '22 at 09:49
  • 4
    This is simple and redable. Keep it as it is – adiga Oct 19 '22 at 09:57
  • 2
    @mousetail if `B` is null. – Richard Dunn Oct 19 '22 at 09:57
  • @mousetail so in my case `A` is a number, `A` can possibly be `null` or can have a `number` value. Basically i want to do something when `A` is `NOT NULL` or if `A` has a value when is not equal to 0 – devludo Oct 19 '22 at 10:05
  • Anyway i think you guys are right i should keep it as it is. Sometimes i'm overthinking the task and end up creating problems even where is not necessary. Thanks! – devludo Oct 19 '22 at 10:10
  • *Basically i want to do something when A is NOT NULL or if A has a value when is not equal to 0* if you want to check for a valid number which is not exactly zero you could just use `if(a)`. – JavaScript Oct 19 '22 at 10:59

2 Answers2

3

You could do :

if([B, null].includes(A)) {
   // ...
}
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
0

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 ) {
Mark Reed
  • 91,912
  • 16
  • 138
  • 175