How to correctly convert from if/else statement to ternary expression?

Viewed 62

If we don’t have a number in ${desc}, we log out extId and if doesn’t have extId, then it goes with empty string.

I tried to convert this:

if (/^\d+$/.test(desc)) {
  console.log(desc);
}
if (!/^\d+$/.test(desc) && exlId != null) {
  console.log(extId);
} else {
  console.log("");
}

to this :

/^\d+$/.test(desc)
  ? desc
  : ""
  ? !/^\d+$/.test(desc) && extId != null
  : ""

But this didn't work. What I do wrong?

3 Answers

If I got your question correctly:

const log =  /^\d+$/.test(desc) ? desc : extId ? extId : "";
// Prints: -------------------------^-------------^-------^

or alternatively:

const log =  /^\d+$/.test(desc) && desc || extId && extId || "";

PS: fix also your typo: exlId !== extId

Here's your ternary statement:

/^\d+$/.test(desc) ? desc : "" ? !/^\d+$/.test(desc) && extId != null : "";

The above statement if written in if-else form:

if (/^\d+$/.test(desc)) {
    console.log(desc);
}
else if ("") {
    console.log(!/^\d+$/.test(desc) && extId != null);
}
else {
    console.log("");
}

You can see the issue here. Now here is the correct ternary statement:

/^\d+$/.test(desc) ? desc : extId ? extId : "";
Related