Last active
May 4, 2022 14:18
-
-
Save wiledal/1888a24fafc11cafba73a8c12ac9d8a0 to your computer and use it in GitHub Desktop.
Template Literal Examples: if-statement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Template literals if-statement example | |
Using a single-line conditional, we can create an if-statements within template literals. | |
*/ | |
function makeHTML(title) { | |
return ` | |
${title ? ` | |
This element has a title, and it is "${title}" | |
` : ` | |
This element does not have a title. | |
`} | |
` | |
} | |
var element1 = document.createElement('div') | |
var element1.innerHTML = makeHTML('This is a title!') | |
// Result: <div>This element has a title, and it is "This is a title!"</div> | |
var element2 = document.createElement('div') | |
var element2.innerHTML = makeHTML() | |
// Result: <div>This element does not have a title.</div> |
For @davidmaxwaterman and others who come here looking for how to use a real if, I made this example: https://gist.github.com/claytongulick/bf05ecebe7a2bbb96b585b74af203eed
Thanks @claytongulick !
and also thank you @wiledal for making these gists! they've been super helpful
thanks.....
Thanks
Thanks
Thanks @claytongulick
Worked. Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I landed here looking to see if I could embed an 'if' statement in a template literal; but this doesn't do that so I'm none the wiser. It might be worth mentioning if the reason for this gist is because 'it' statements aren't possible inside template literals (if that is indeed the case).