Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator in string template

There is a compact way to build a string with optional parameters like this?

let q = `CREATE "a"
            ${this.date ? ` SET date = '${this.date}'` : ''}
            ${this.description ? ` SET description = '${this.description}'` : ''}
            RETURN n`;

without that else case returning an empty string ''?

Edit: The current results is:

CREATE "a"


RETURN n

This is just an aesthetic issue, I would prefer not having those empty lines


Using boolean operator && doesn't work (it returns undefined as string):

${this.date && ` SET date = '${this.date}'`}
like image 302
alfredopacino Avatar asked Oct 16 '25 15:10

alfredopacino


1 Answers

You can use condition && value || "", but that's almost equivalent to using ternary operator.

Another available option is to try tagged template here that discards empty values:

    let date;
    let description = "description";

    function nonEmpty(parts) {
        var res = parts[0];
        for (var i=1; i<parts.length; i++) {
            if (arguments[i]) // you might want to handle `0` different
                res += arguments[i];
            res += parts[i];
        }
        return res;
    }

    console.log(nonEmpty`Date :: ${date} and Description :: ${description}`);
like image 156
Pawan Singh Avatar answered Oct 18 '25 03:10

Pawan Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!