Template Literals
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
Template literals (or template strings) are strings that begin and end with backticks.
const templateLiteral = `This is a template literal`
Let’s say you have a function, sayName that logs the first name and last name of a person.
To split the firstName and lastName variables up, what you’ve done so far is concatenate a space character between the two variables.
const sayName = (firstName, lastName) => {
console.log(firstName + ' ' + lastName)
}
sayName('Zell', 'Liew') // Zell Liew
This is clunky. You can skip the clunky string concatenation process by using template literals.
To do so, you wrap code with ${}. Anything within ${} in a template literal signifies JavaScript; anything outside ${} signifies a normal string.
const sayName = (firstName, lastName) => {
console.log(`${firstName} ${lastName}`)
}
sayName('Zell', 'Liew') // Zell Liew
Template literals let you create strings that span multiple lines, like this:
const multi = `Once upon a time,
In a land far far away,
there lived a witch,
who could change night into day`
console.log a string that contains a variable with template literalsconsole.log a string that spans multiple lines with template literalsconsole.log a string that contains a variable with template literalsconst thing = 'world'
console.log(`Hello ${thing}`)
console.log a string that spans multiple lines with template literalsconsole.log(`This
is
a
string
that
spans
many
many
many
lines`)