Using conditionals inside template literals

Viewed 35536

I know there are more elegant ways to define a string with variables included, but if I want to add a conditional in pre ES6 I would do..

var a = "text"+(conditional?a:b)+" more text"

now with template literals I would do..

   let a;
   if(conditional) a = `test${a} more text`;
   else a = `test${b} more text`;

Is there a more elegant way to implement this conditional? is it possible to include if shortcut?

4 Answers

You can also expand this a bit further and use placeholders inside such a conditional.

It really depends on the use case you have which is the most readable.

Some examples:

// example 1
const title = 'title 1';
const html1 = `${title ? `<h2>${title}</h2>` : '<h2>nothing 1</h2>'}`

document.getElementById('title-container-1').innerHTML = html1;

// example 2
const title2= 'title 2';
const html2 = `
 ${title2 ? 
   `<h2>${title2}</h2>` : 
   "<h2>nothing 2</h2>"
  }`

document.getElementById('title-container-2').innerHTML = html2;

// example 3
const object = {
 title: 'title 3'
};

const html3 = `
 ${(title => {
      if (title) {
        return `<h2>${title}</h2>`;
      }
    return '<h2>Nothing 3</h2>';
  })(object.title)
   }
`;

document.getElementById('title-container-3').innerHTML = html3;
<div id="title-container-1"></div>
<div id="title-container-2"></div>
<div id="title-container-3"></div>

(source)

If you have a simple condition to check, use the ternary operator, as it as been said, but if you have more complex or nested conditions, just call a function in this way:

const canDrink = (age, hasToDrive) => {
  if (age >= 18 && !hasToDrive ) {
    return 'Yeah, no problem'
  } else if ( age >= 18 && hasToDrive ){
    return 'Maybe not that much'
  } else {
    return 'Not at all'
  }
}

console.log(`Can you drink tonight? ${ canDrink(21, true) }`) // Can you drink tonight? Maybe not that much
let t1 = "hey";
let t2 = "there";
console.log(`${t1}${t2 ? `(${t2})` : ''}`);
Related