Skip to content

Instantly share code, notes, and snippets.

@wiledal
Last active May 4, 2022 14:18
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save wiledal/1888a24fafc11cafba73a8c12ac9d8a0 to your computer and use it in GitHub Desktop.
Save wiledal/1888a24fafc11cafba73a8c12ac9d8a0 to your computer and use it in GitHub Desktop.
Template Literal Examples: if-statement
/*
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>
@davidmaxwaterman
Copy link

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).

@claytongulick
Copy link

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

@oneezy
Copy link

oneezy commented Mar 7, 2018

Thanks @claytongulick !
and also thank you @wiledal for making these gists! they've been super helpful

@hrishi7
Copy link

hrishi7 commented Mar 25, 2018

thanks.....

@sulenchy
Copy link

Thanks

@GarciaFreelancer
Copy link

Thanks

@MarekKadas
Copy link

MarekKadas commented Oct 9, 2021

@pbanigo
Copy link

pbanigo commented Apr 15, 2022

Worked. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment