Template Strings Flashcards
What is the es6 answer to this?
var text = ‘my dog is: ‘ + 5 + ‘ years old’
Template strings
What character do template strings use?
`
backtext
How do you insert a variable in backtext?
Using ${ variable }
Do you need plusses in back text?
No. let age = 5; const text = `my dog is: ${age} years old'
Can you run any javascript inside of backtext?
Yes const text = `my dog is: ${age * 7} years old'
How does ES6 template string behave in terms of new lines and spacing etc?
You can write them without any \
They preserve new lines and tabbing.
Are Template String nestable?
Yes
How would you create a list in a template string from an objects data?
const dogs = { name: hugo, age: 5, etc }
const markup = ` <ul> ${dogs.map(dog => `<li>${dog.name} is ${dog.age}</li>`)} </ul> `;
The output contains comma’s, why is this?
Because map returns an array, we just join with nothing.
const markup = ` <ul> ${dogs.map(dog => `<li>${dog.name} is ${dog.age}</li>`).join('')} </ul> `;
If you need looping inside of a template string what function could you use?
A map arrow function.
How would you run an external function to populate some template data?
const template = ` ${ renderKeywords(beer.keywords) } ` The function can then do a map and return the list items from elsewhere
How do you use an if statement in a template string?
show only song.featuring when it is present.
Using a ternary operator.
${song.featuring ? ` (featuring ${song.featuring} ` : ‘’ }
Name two reasons Tagged template are useful for.
pre-processing the templates information in an external function to embellish or santitize user information.
creating an element with javascript?
document.createElement(‘p’);