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.
function sayName(firstName, lastName) { console.log(firstName + ' ' + lastName)}
sayName('Zell', 'Liew') // Zell LiewThis 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.
function sayName(firstName, lastName) { console.log(`${firstName} ${lastName}`)}
sayName('Zell', 'Liew') // Zell LiewMulti-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.loga string that contains a variable with template literalsconsole.loga string that spans multiple lines with template literals
console.log a string that contains a variable with template literals
const thing = 'world'console.log(`Hello ${thing}`)console.log a string that spans multiple lines with template literals
console.log(`Thisisastringthatspansmanymanymanylines`)Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson