Introduction
Template literals, or also known as template strings, allow us, the developers to use strings or embedded expressions the form of a string.
Back-Tick syntax
Template Literals use back-ticks(` `
) rather than quotes ("") to define a string
let text = `This is a Template Literal`
With template literals, you can use both, single quote ('') and double quotes ("") inside a string
let text1 = `This is a string with 'single' & "double" quotes in it.`
The template literals not only make it easy to include quotations but also make our code look cleaner
// Template Literals also make it easy to write multiline strings.
let text = `Practice
is the key
to success`
Interpolation
Template Literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.
The syntax is ${...}
const name = 'Mursal'
console.log(`Hello ${name}`)
// Output => Hello Mursal
const result = 1 + 2
console.log(`$(result < 10 ? 'Less' : 'More'}`)
// Output => More
HTML Templates
Let's explore the code below, and comment down with the output 😜
let header = "Template Literals"
let tags = ["HTML", "CSS", "JavsScript"]
let html = `<h2>${header}</h2></ul>`
for (const tag of tags) {
html += `<li>${tag}</li>`
}
html += `</ul>`
document.querySelector("body").innerHTML = html
Top comments (0)