JavaScript Template Literals

Mursal Furqan Kumbhar - Sep 27 '22 - - Dev Community

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`
Enter fullscreen mode Exit fullscreen mode

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.`
Enter fullscreen mode Exit fullscreen mode

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`
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .