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!
Template Literals
Template literals (or template strings) are strings that begin and end with backticks.
const templateLiteral = `This is a template literal`
It’s easy to log variables with template literals
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
Multi-line strings
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`
Exercise
console.log
a string that contains a variable with template literals
console.log
a string that spans multiple lines with template literals