Inserting if statement inside ES6 template literal
You'll need to move your logic into a function or use the ternary operator:
`${result['color 5'] ? 'color 5 exists!' : 'color 5 does not exist!'}`
Additional example based on comment:
`${result['color 5'] ?
`<div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>`
: ''}`
From the MDN article on template strings:
Template literals are string literals allowing embedded expressions.
So, you can also use an IIFE (immediately invoked function expression). Eg: (() => { ... })()
.
Though, I would argue that if you need more complicated logic than a ternary expression within your template strings, you should consider refactoring your code. However, since this hasn't been presented by the other answers, here's an approach using IIFEs. This can be useful in cases where a ternary expression would suffice, but you prefer reading your branching logic in imperitive form; or in cases where you're embedding other multi-line template strings.
Let me make up an example for you:
/* Note: I'm using a tagged template literal for HTML templates here,
* similar to the one provided by www.npmjs.com/package/lit-html.
*/
html`
<div class="example">
${(() => {
if (result['color 5']) {
return html`
<div class="color-preview" style="background-color: ${result['color 5']}"></div>
<span> Here's your color #5 </span>
`
} else {
return html`<div>You don't have a 5th color</div>`
}
})()}
</div>
`
Since a function body can contain more than only expressions, this technique allows you to use any JavaScript syntax "within" your template string.
you can use the nullish coalescing operator inside the template literal.
`${result['color 5'] ?? `Color 5 exists`}`
A better way is to create default parameters for the function.
const renderHello = (name = "new member") => `Hello ${name}`;
console.log(1, renderHello());
console.log(2, renderHello("James"));
// 1 Hello new member
// 2 Hello James
There may be times you don't want to render anything if the condition is false
, like how you have it in your question. You can therefore do something like this:
(Note: it's also possible to nest template literals inside each other when the nested one is inside a ${}
)
const html = `
<div>
<div>
Lots of HTML stuff
</div>
<div>
${result['color 5'] && `
<div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>
`}
</div>
`;
This works because, unlike other languages, in Javascript, logical operators (&&
and ||
) do not (necessarily) return true
or false
.
The logical AND operator (&&
):
Javascript returns either the first falsy variable, and if none are found, the last truthy variable.
The logical OR operator (||
)
Javascript returns either the first truthy variable, and if none are found, the last falsy variable.
You can see this in action here:
console.log(true && true) // true
console.log(false && true) // false
console.log("a" && "b"); // b
console.log(false && "b"); // false
console.log(0 && "b"); // 0
console.log("a" && NaN); // NaN
This is used very commonly in JSX.