Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

if we don’t have a number in ${desc}, we take 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
            : ""

what I do wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading