codestarter
codestarter

Reputation: 15

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

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?

Upvotes: 1

Views: 158

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

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

Upvotes: 1

che
che

Reputation: 101

Might be Your syntax is wrong to implement the multiple conditions in the ternary operator

It should be like

condition1 ? condition2 ? Expression1 : Expression2 : Expression3

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

check out this for more info https://www.geeksforgeeks.org/how-to-use-multiple-ternary-operators-in-a-single-statement-in-javascript/#:~:text=In%20the%20above%20syntax%2C%20we,then%20the%20output%20is%20Expression1.

Upvotes: 1

The Coding Fox
The Coding Fox

Reputation: 1595

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 : "";

Upvotes: -1

Related Questions