DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for JavaScript Template Literals
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

JavaScript Template Literals

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

Top comments (0)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!