MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Template Literals0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
HomeTutorialsJavaScript for IntermediateTemplate Literals
Destructuring Arrays and Objects

Template Literals

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

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:

1const user = {
2 name: "Sumit",
3 courses: ["Full-Stack Dev", "Data Analysis", "Power BI"]
4};
5 
6const profileHTML = `
7 <div class="user-card">
8 <h2>${user.name}</h2>
9 <ul class="course-list">
10 ${user.courses.map(c => `<li>${c}</li>`).join("")}
11 </ul>
12 </div>
13`;

2. Tagged Template Functions Explained

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

1tagFunction`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).
1function debugTag(strings, ...values) {
2 console.log("Static strings:", strings);
3 console.log("Dynamic values:", values);
4}
5 
6const item = "Laptop";
7const price = 45000;
8 
9debugTag`Product: ${item} costs ₹${price}.`;
10// Static strings: ["Product: ", " costs ₹", "."]
11// 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):

1function safeHTML(strings, ...values) {
2 return strings.reduce((accumulator, str, i) => {
3 let value = values[i - 1];
4 
5 if (typeof value === "string") {
6 // Escape harmful HTML characters
7 value = value
8 .replace(/&/g, "&amp;")
9 .replace(/</g, "&lt;")
10 .replace(/>/g, "&gt;")
11 .replace(/"/g, "&quot;")
12 .replace(/'/g, "&#39;");
13 }
14 
15 return accumulator + (value ?? "") + str;
16 });
17}
18 
19const userComment = `<script>stealCookies();</script>Amazing tutorial!`;
20const cleanMarkup = safeHTML`<div class="comment">${userComment}</div>`;
21 
22console.log(cleanMarkup);
23// <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:

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

Interactive Quiz• Knowledge Check

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

Previous LessonNext Lesson
Block Scope with let & constDestructuring Arrays and Objects

Practice Quiz

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

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext