Template Literals
This lesson explains Template Literals with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.
ES6+ Template Literals Overview
Template literals are a modern JavaScript string syntax introduced
in ES6. They use backticks instead of quotes and allow embedded
expressions, multi-line strings, and cleaner dynamic text building.
Template literals are widely used for logging, HTML snippets, API
URLs, user messages, SQL-like query strings, and any place where
variables need to be inserted into text without messy
concatenation.
| Feature | Description |
| Introduced In | ES6 (ECMAScript 2015) |
| Syntax | Backticks: `text` |
| Interpolation | ${expression} |
| Multi-line Support | Yes |
| Expression Support | Any valid JavaScript expression |
| Common Uses | Messages, HTML, URLs, logs, dynamic labels |
Basic Template Literal Example
const name = "Alex";
const greeting =
`Hello, ${name}!`;
console.log(greeting);
Template literals use backticks and insert values with
${expression}. This is cleaner and easier
to read than string concatenation.
How Template Literals Work
JavaScript evaluates expressions inside
${ } and converts the result into a string
as part of the final template literal output.
| Step | Description | Example Syntax |
| Use Backticks | Start a template literal string. | `Welcome back` |
| Insert Variable | Embed a value directly. | `Hello, ${name}` |
| Run Expression | Evaluate JavaScript inside the placeholder. | `Total: ${price * qty}` |
| Write Multiple Lines | Preserve line breaks naturally. | `Line 1\nLine 2` |
| Build Output | Combine text and dynamic values. | `Order #{id}` |
| Use Result | Log, render, or return the string. | console.log(message) |
String Interpolation Example
const product = "Laptop";
const price = 999;
const quantity = 2;
const summary =
`You ordered ${quantity} ${product}(s) for ${price * quantity}.`;
console.log(summary);
Any valid JavaScript expression can appear inside
${ }, including math, function calls, and
ternary operators.
Multi-line Template Literal
const emailBody =
`Hello Alex,
Thank you for joining our platform.
Your account is now active.
Regards,
The Team`;
console.log(emailBody);
Template literals preserve line breaks, making them ideal for
emails, markdown snippets, SQL queries, and formatted messages.
Use Expressions Inside Templates
const score = 82;
const result =
`Your score is ${score}. Status: ${
score >= 90
? "Excellent"
: score >= 70
? "Good"
: "Needs Improvement"
}`;
console.log(result);
Conditional expressions, function calls, and object property access
all work inside template literal placeholders.
Call Functions in Template Literals
function formatPrice(amount) {
return `${amount.toFixed(2)}`;
}
const item = "Monitor";
const price = 249.5;
const label =
`${item} - ${formatPrice(price)}`;
console.log(label);
Function calls inside template literals help keep formatting logic
reusable while still producing readable string output.
Build HTML with Template Literals
const user = {
name: "Alex",
role: "Admin"
};
const card =
`
<article class="user-card">
<h2>${user.name}</h2>
<p>Role: ${user.role}</p>
</article>
`;
document
.querySelector("#app")
.insertAdjacentHTML(
"beforeend",
card
);
Template literals are commonly used to generate HTML fragments.
Always sanitize untrusted data before inserting it into the DOM.
Build URLs with Template Literals
const baseUrl =
"https://api.example.com";
const userId = 42;
const page = 2;
const limit = 10;
const endpoint =
`${baseUrl}/users/${userId}/posts?page=${page}&limit=${limit}`;
console.log(endpoint);
Dynamic URLs are much easier to read with template literals than
with multiple string concatenations and manual separator handling.
Nested Template Literals
const theme = "dark";
const label = "Settings";
const buttonClass =
`btn btn-${theme}`;
const button =
`<button class="${buttonClass}">${label}</button>`;
console.log(button);
You can use template literals inside other template literal
expressions when building more complex dynamic strings.
Escape Backticks and Dollar Signs
const message =
`Use backticks like this: \`code\``;
const priceNote =
`Price uses the ${amount} placeholder syntax.`;
const literalDollar =
"Price is \\$49";
console.log(message);
console.log(priceNote);
console.log(literalDollar);
Escape backticks with a backslash when you need literal backtick
characters inside a template literal. Use a normal string when you
want to show the ${ } syntax itself without
interpolation.
Template Literals vs Concatenation
const city = "Paris";
const country = "France";
const oldWay =
"Welcome to " +
city +
", " +
country +
"!";
const modernWay =
`Welcome to ${city}, ${country}!`;
console.log(oldWay);
console.log(modernWay);
Template literals reduce visual noise and make dynamic strings
easier to scan, especially when several variables are involved.
Template Literal Features
| Feature | Description | Example |
| Backtick Strings | Modern string delimiter. | `Hello` |
| Interpolation | Insert values into text. | `Hi ${name}` |
| Multi-line Text | Preserve line breaks. | `Line 1\nLine 2` |
| Expressions | Evaluate JavaScript inline. | `${a + b}` |
| Tagged Templates | Custom processing with a tag function. | html`<p>Hi</p>` |
Common Template Literal Use Cases
- User-facing messages and notifications.
- HTML and SVG snippets in client-side rendering.
- API endpoints and query string construction.
- Console logs and debugging output.
- File paths and configuration strings.
- Email, markdown, and multi-line formatted content.
Template Literal Best Practices
- Use template literals instead of concatenation for dynamic strings.
- Keep expressions inside
${ } short and readable. - Extract complex formatting into helper functions.
- Sanitize user input before inserting it into HTML templates.
- Use multi-line templates for readable formatted text blocks.
- Prefer tagged templates when repeated custom processing is needed.
- Avoid putting large business logic directly inside placeholders.
Common Template Literal Mistakes
- Using single or double quotes instead of backticks.
- Forgetting the dollar sign before curly braces.
- Inserting unsanitized user data into HTML templates.
- Putting too much logic inside one placeholder expression.
- Assuming template literals automatically escape HTML.
- Creating deeply nested templates that are hard to read.
- Mixing concatenation and template literals unnecessarily.
Template Literals vs Normal Strings
| Feature | Template Literals | Normal Strings |
| Syntax | Backticks | Single or double quotes |
| Variable Insertion | ${value} | Concatenation with + |
| Multi-line | Built in | Requires \n |
| Readability | Better for dynamic text | Fine for static text |
Key Takeaways
- Template literals use backticks and support embedded expressions.
${expression} inserts values and evaluates JavaScript inline. - They make multi-line strings and dynamic messages much cleaner.
- They are ideal for URLs, logs, labels, and HTML snippets.
- For advanced custom processing, learn tagged template literals next.
Pro Tip
If a template literal starts getting crowded with logic, move the
complex expression into a variable or helper function first, then
interpolate the result.