JavaScript Notes
Master JavaScript template literals: string interpolation, multi-line strings, expressions, nested templates, tagged templates, and real-world HTML generation examples.
What are Template Literals?
Template literals are strings wrapped in backticks (` ``) instead of single or double quotes. They allow you to:
- Embed expressions directly inside strings using
${expression} - Write multi-line strings naturally without
\n - Use complex expressions like function calls, ternaries, and math
Think of template literals as a smart string that can evaluate code inside it. Where old strings were static text, template literals are dynamic text with fill-in-the-blank slots.
Basic String Interpolation
const name = "Priya";
const course = "JavaScript";
const lessons = 42;
// Old way
console.log("Hello " + name + "! Welcome to " + course + " with " + lessons + " lessons.");
// Template literal
console.log(`Hello ${name}! Welcome to ${course} with ${lessons} lessons.`);Hello Priya! Welcome to JavaScript with 42 lessons. Hello Priya! Welcome to JavaScript with 42 lessons.
Expressions Inside ${}
You can put any valid JavaScript expression inside ${}:
const a = 10;
const b = 20;
// Arithmetic
console.log(`Sum: ${a + b}`);
console.log(`Product: ${a * b}`);
console.log(`Is a > b? ${a > b}`);
// Method calls
const name = " riya sharma ";
console.log(`Name: ${name.trim().toUpperCase()}`);
// Ternary operator
const score = 75;
const result = `Score: ${score} — ${score >= 60 ? "Passed ✅" : "Failed ❌"}`;
console.log(result);Sum: 30 Product: 200 Is a > b? false Name: RIYA SHARMA Score: 75 — Passed ✅
Multi-line Strings
// Old way — backslash or concatenation
const oldMsg = "Line 1\n" +
"Line 2\n" +
"Line 3";
// Template literal — just press Enter
const newMsg = `Line 1
Line 2
Line 3`;
console.log(newMsg);Line 1 Line 2 Line 3
Multi-line HTML template
const user = { name: "Aman", role: "Admin", email: "aman@x.com" };
const profileCard = `
<div class="profile-card">
<h2>${user.name}</h2>
<span class="badge">${user.role}</span>
<p>Email: ${user.email}</p>
</div>
`.trim();
console.log(profileCard);<div class="profile-card"> <h2>Aman</h2> <span class="badge">Admin</span> <p>Email: aman@x.com</p> </div>
Nested Template Literals
Courses: JavaScript, React, Node.js Welcome back, JavaScript!
Function Calls Inside Template Literals
function formatCurrency(amount, currency = "₹") {
return `${currency}${amount.toLocaleString("en-IN")}`;
}
function getDiscount(price, percent) {
return price - (price * percent / 100);
}
const originalPrice = 15000;
const discountPercent = 20;
const invoice = `
Original Price: ${formatCurrency(originalPrice)}
Discount (${discountPercent}%): ${formatCurrency(originalPrice * discountPercent / 100)}
Final Price: ${formatCurrency(getDiscount(originalPrice, discountPercent))}
`.trim();
console.log(invoice);Original Price: ₹15,000 Discount (20%): ₹3,000 Final Price: ₹12,000
Template Literals with Arrays and Objects
=== Marks Report === Alice: 92 Bob: 78 Charlie: 85 =================== Average: 85.0
Tagged Template Literals (Advanced)
A tagged template is a function that processes a template literal. The function receives the string parts and interpolated values separately.
Learning [JavaScript] in [2026] is awesome!
Practical tagged template: SQL-safe query builder
SELECT * FROM users WHERE name = 'Riya\'; DROP TABLE users;--' AND age = 22
Real World Use Cases 🌍
1. Dynamic error messages
function validateAge(age, min = 18) {
if (age < min) {
throw new Error(`Age ${age} is below minimum required age of ${min}.`);
}
return `Age ${age} is valid.`;
}
try {
console.log(validateAge(25));
console.log(validateAge(15));
} catch (e) {
console.log(e.message);
}Age 25 is valid. Age 15 is below minimum required age of 18.
2. Build email template
function generateEmail({ name, course, deadline }) {
return `
Subject: Enrollment Confirmation
Dear ${name},
Thank you for enrolling in ${course}.
Please complete your first assignment by ${deadline}.
Best regards,
WoHoTech Team
`.trim();
}
console.log(generateEmail({
name: "Rahul",
course: "JavaScript Master Course",
deadline: "June 20, 2026"
}));Subject: Enrollment Confirmation Dear Rahul, Thank you for enrolling in JavaScript Master Course. Please complete your first assignment by June 20, 2026. Best regards, WoHoTech Team
3. Debug logging with context
[DEBUG] user: {"name":"Tara","age":25} (object)
[DEBUG] name: "Tara" (string)
[DEBUG] age: 25 (number)Comparison: Old Style vs Template Literals
| Feature | Old Style " " / ' ' | Template Literals ` ` |
|---|---|---|
| Variable embedding | "Hello " + name | ` Hello ${name} ` |
| Multi-line | "line1\n" + "line2" | ` line1↵line2 ` |
| Expressions | Separate concatenation | ${a + b}, ${fn()} |
| Readability | Poor with many variables | Clean and natural |
| Nesting | Difficult | Supports nested backticks |
| Tagged templates | ❌ Not possible | ✅ Powerful feature |
Common Mistakes ❌
1. Using quotes instead of backticks
// ❌ Wrong — ${name} printed literally
const name = "Priya";
console.log("Hello ${name}!"); // "Hello ${name}!"
// ✅ Correct — use backticks
console.log(`Hello ${name}!`); // "Hello Priya!"2. Putting logic in template that belongs in a variable
3. Unintended whitespace in multi-line templates
// ❌ Leading whitespace included
function buildHTML() {
return `
<div>Hello</div>
`;
}
// The string starts with a newline and has indentation spaces
// ✅ Use .trim() to remove surrounding whitespace
function buildHTML2() {
return `
<div>Hello</div>
`.trim();
}Interview Questions 🎯
Q1. What are template literals and what are they used for? > Template literals are strings using backticks that support string interpolation (${expr}), multi-line strings, and tagged template functions. They replaced messy string concatenation.
Q2. What can you put inside ${} in a template literal? > Any valid JavaScript expression: variables, arithmetic, function calls, ternary operators, method calls, object access, array methods, etc.
Q3. How are template literals different from regular strings? > They use backticks, support ${expression} interpolation, support natural multi-line without \n, and can be "tagged" for advanced processing.
Q4. What are tagged template literals? > A tag is a function placed before a template literal. It receives the string parts and values separately, allowing custom processing like sanitization, internationalization, or DSL creation.
Q5. How do you write a backtick inside a template literal? > Escape it with a backslash: ` It costs \5\ dollars `
Q6. Are template literals faster than string concatenation? > Performance is virtually identical in modern engines. The benefit is readability and maintainability, not speed.
Q7. Can you nest template literals? > Yes: ` outer ${condition ? inner ${value} : "default"} ` — inner backticks create a new template literal within the expression.
Key Takeaways 🏁
- Template literals use backticks `
`` — not quotes ${}can hold any JavaScript expression — variable, function call, ternary, math- Multi-line strings are natural — just press Enter
- Use
.trim()when multi-line templates have unwanted leading/trailing whitespace - Tagged templates enable advanced processing — great for security (SQL escaping, XSS prevention)
- Always prefer template literals over
+concatenation for readability - Template literals are syntactic sugar — they compile to string concatenation internally
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Template Literals (ES6) - Complete Guide with Tagged Templates.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, strings, template, literals
Related JavaScript Master Course Topics