heron
heron

Reputation: 3661

Working with ternary operators in Javascript

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?

Upvotes: 0

Views: 91

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213193

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

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1073968

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

Upvotes: 3

Related Questions