Using conditionals inside template literals
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
Use this:
let a = `test${conditional ? a : b} more text`;
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)