0

I have this line of code in JS for handing payments, but I'm not sure what it's doing as I've never seen some of this syntactic sugar before.

var fund = response.card != null ? response.card[0] : response.bank_acct[0];
Alain Goldman
  • 2,786
  • 4
  • 39
  • 70

2 Answers2

5

This is the conditional operator. Instead of writing this:

var fund;
if(response.card != null )
{
    fund = response.card[0]
}
else
{
    fund = response.bank_acct[0];
}

you could write this:

var fund = response.card != null ? response.card[0] : response.bank_acct[0];
Christos
  • 50,311
  • 8
  • 62
  • 97
  • @Downvoter could you please explain me where the answer is wrong? Thank you in advance. – Christos Jan 22 '15 at 17:40
  • Nothing wrong with your answer per se, but I question encouraging the use of SO as a Q&A resource for people who have not bothered to learn the basic syntax of the language. You also could have pointed him to authoritative pages about `?`, and/or given suggestions to him about how to find such resources on his own, so he doesn't have to post to SO every time he sees a syntactic construct he doesn't know, and/or commented on its long history in other programming languages, and/or commented on why one form might be preferred to the other in what kinds of cases. –  Jan 22 '15 at 17:58
3

It works the same as (and is considered shorthand for) this conditional statement:

var fund;
if (response.card != null) {
  fund = response.card[0];
} else {
  fund = response.bank_acct[0];
}
Andy
  • 39,764
  • 8
  • 53
  • 80