DEV Community

Cover image for JavaScript Template Literals
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

1

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay