2

Here is a piece of code I have in several places in my code:

req = this.getActiveRequestById(message.trans_id);
if (!req) {
    break;
}

How can I rewrite this as a one-liner?

EDIT I want to clarify that I need to store the return value in req for later use.

user1283776
  • 19,640
  • 49
  • 136
  • 276
  • 1
    `if (!this.getActiveRequestById(message.trans_id)) break;`? What's the problem here? – nick zoum Feb 13 '19 at 12:03
  • Possible duplicate of [How do you use the ? : (conditional) operator in JavaScript?](https://stackoverflow.com/questions/6259982/how-do-you-use-the-conditional-operator-in-javascript) – Liam Feb 13 '19 at 12:04
  • *How can I rewrite this as a one-liner?* I would also question why here? why is this is a problem? – Liam Feb 13 '19 at 12:05
  • 1
    What are you `break`ing from? – Bergi Feb 13 '19 at 12:14
  • 1
    @Bergi From a swtich case – user1283776 Feb 13 '19 at 12:16
  • 3
    @user1283776 And else you need to fall-through? If you are asking how to simplify your code and avoid duplicating parts, please post the whole code so that we can suggest an appropriate abstraction. – Bergi Feb 13 '19 at 12:19
  • Thanks @Bergi: I'll try to keep your advise in mind for the future – user1283776 Feb 13 '19 at 12:54

2 Answers2

3

Remove var assignment and apply the condition directly to the value:

if (!this.getActiveRequestById(message.trans_id)) break;

I would not suggest it but if you need to set a variable in a one liner if condition it should work:

 if (!(req = this.getActiveRequestById(message.trans_id))) break;

Notice that it generates confusion between comparison and assignment.

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
1
if (!(reg = this.getActiveRequestById(message.trans_id))) break;
Krzysztof Janiszewski
  • 3,763
  • 3
  • 18
  • 38