Template Literals0%

Template Literals

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Template Literals & Tagged Templates

Beyond basic ${...} string interpolation, ES6 Template Literals provide an advanced metaprogramming feature called Tagged Templates. Tagged templates allow developers to parse template literals with custom functions, powering libraries like styled-components, GraphQL (gql), and SQL query sanitizers.


1. Advanced String Interpolation & Nesting

Template literals can be nested inside other template literals, enabling declarative, dynamic HTML generation:

JavaScript
const user = {
name: "Sumit",
courses: ["Full-Stack Dev", "Data Analysis", "Power BI"]
};
 
const profileHTML = `
<div class="user-card">
<h2>${user.name}</h2>
<ul class="course-list">
${user.courses.map(c => `<li>${c}</li>`).join("")}
</ul>
</div>
`;

2. Tagged Template Functions Explained

A Tagged Template is an advanced function call where the function precedes the template literal without parentheses:

JavaScript
tagFunction`Hello ${name}, you have ${count} messages.`;

How JavaScript Dissects the Arguments:

When you tag a template literal, JavaScript breaks it into:

  1. 1
    An array of static strings (strings).
  2. 2
    The evaluated expression values as subsequent arguments (...values).
JavaScript
function debugTag(strings, ...values) {
console.log("Static strings:", strings);
console.log("Dynamic values:", values);
}
 
const item = "Laptop";
const price = 45000;
 
debugTag`Product: ${item} costs ₹${price}.`;
// Static strings: ["Product: ", " costs ₹", "."]
// Dynamic values: ["Laptop", 45000]

3. Real-World Use Case: Automatic XSS Sanitizer

Tagged templates allow you to build custom security layers that automatically sanitize user-generated inputs to prevent Cross-Site Scripting (XSS):

JavaScript
function safeHTML(strings, ...values) {
return strings.reduce((accumulator, str, i) => {
let value = values[i - 1];
 
if (typeof value === "string") {
// Escape harmful HTML characters
value = value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
 
return accumulator + (value ?? "") + str;
});
}
 
const userComment = `<script>stealCookies();</script>Amazing tutorial!`;
const cleanMarkup = safeHTML`<div class="comment">${userComment}</div>`;
 
console.log(cleanMarkup);
// <div class="comment">&lt;script&gt;stealCookies();&lt;/script&gt;Amazing tutorial!</div>

4. Raw Strings: String.raw

The String.raw tag accesses the raw, unescaped string text without processing escape characters like \n or \t:

JavaScript
// Without String.raw, \n is treated as a newline:
const formatted = `Line 1\nLine 2`;
 
// With String.raw, \n is treated as raw characters \ and n:
const rawFilePath = String.raw`C:\Development\new_project\test.js`;
console.log(rawFilePath); // "C:\Development\new_project\test.js"

Interactive Quiz

Practice Quiz

Question 1
What is a "Tagged Template" in JavaScript?
Question 2
In a tagged template fn Hello ${name}! `, what does the first parameter to fn` contain?
Question 3
What is the primary purpose of the built-in String.raw tag?
Question 4
Which popular modern frontend libraries rely extensively on tagged template literals?
Question 5
In safeHTML <p>${input}</p> `, how many string fragments are in the strings` array?
Next Lesson

Destructuring Arrays and Objects

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext