0

I worked with ternary operators but never seen before something like that:

.replace('{{name}}', ticket['areaName'] ? ticket['areaName'] : !area && ticket['catName'] ? ticket['catName'] : '--')

Can anyone translate it to human language or standart if else pseudo-code?

2
  • 1
    eeeeeeeeew kill it with fire. Commented Sep 22, 2013 at 15:01
  • What part don't you understand? Commented Sep 22, 2013 at 15:01

2 Answers 2

3

It's just a conditional operator expression where the expression in the third operand is another conditional operator expression:

var temp;
if (ticket['areaName']) {              // First conditional's first operand (test)
    temp = ticket['areaName'];         // First conditional's second operand (true case expression)
}
// All of the following is the first conditional's third operand (the false case expression)
else if (!area && ticket['catName']) { // Second conditional's first operand (test)
    temp = ticket['catName'];          // Second conditional's second operand (true case expression)
}
else {
    temp = '--';                       // Second conditional's third operand (false case expression)
}
/*...*/.replace('{{name}}', temp);

(And yeah, I probably would have broken it up, at least with parens and newlines. No need to make life hard on people trying to read one's code.)

Sign up to request clarification or add additional context in comments.

Comments

2

Let's prettify your code a little bit, so that you can visualize it easily:

.replace('{{name}}', ticket['areaName']   // if
                        ? ticket['areaName']   // then
                        : !area && ticket['catName']  // else if
                               ? ticket['catName']    // then
                               : '--')                // else

So, basically the 3rd expression of the 1st conditional operator is itself a conditional operator. It's basically an if-else if-else ladder:

var replacement;

if (ticket['areaName']) {
    replacement = ticket['areaName'];
} else if (!area && ticket['catName']) {
    replacement = ticket['catName'];
} else {
    replacement = '--';
}

.replace('{{name}}', replacement);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.