JavaScript Template Literals
Learn how template literals simplify string creation, interpolation, and advanced formatting in modern JavaScript.
Why Use Template Literals?
Template literals, introduced in ES6, provide a powerful and readable way to work with strings in JavaScript. They use backticks (``) instead of quotes and enable interpolation, multi-line text, and tagged templates.
Compared to traditional string concatenation with `+`, template literals are easier to write and maintain, especially when embedding variables or expressions.
Basic Interpolation
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!Use `${...}` inside backticks to insert variables or expressions directly into strings.
Multi-Line Strings
Template literals preserve whitespace and line breaks, making it simple to write multi-line strings without escape characters.
Creating a Multi-Line String
const poem = `Roses are red
Violets are blue
Template literals make
Multi-line easy to do.`;
console.log(poem);Backticks allow you to write strings that span multiple lines naturally.
Expression Embedding
You can embed any JavaScript expression inside a template literal. The expression is evaluated and its result inserted into the string.
Embed Expressions
const a = 5;
const b = 10;
console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);
// Output: Fifteen is 15 and not 20.Expressions inside `${}` can be arithmetic, function calls, ternary operators, etc.
Tagged Template Literals
Tagged templates allow you to customize how template literals are processed by passing them to a function. The tag function receives an array of string literals and values, enabling advanced processing such as localization, escaping, or styling.
Basic Tag Function
function highlight(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}<span class="highlight">${str}${values[i] || ''}</span>`,
''
);
}
const user = 'Bob';
const tagged = highlight`Hello, ${user}!`; // calls highlight
console.log(tagged);The tag function can manipulate or escape values before constructing the final string.
Safe HTML Escaping with Tags
function safeHTML(strings, ...values) {
const escape = (str) =>
str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
return strings.reduce((acc, str, i) =>
acc + str + (values[i] ? escape(values[i]) : ''),
''
);
}
const userInput = '<script>alert(1)</script>';
const message = safeHTML`User said: ${userInput}`;
console.log(message);
// Output: User said: <script>alert(1)</script>Tagged templates enable custom escaping to prevent XSS attacks when inserting untrusted values into HTML.
Raw Strings
You can access the raw string content (without processing escape sequences) using the `String.raw` tag or by defining your own tag.
Using String.raw
console.log(String.raw`First line\nSecond line`);
// Output: First line\nSecond line (no actual newline)`String.raw` returns the string exactly as typed, useful for regex patterns or file paths.
Nesting Template Literals
You can nest template literals inside expressions for dynamic content generation.
Nested Literal Example
const name = 'Alice';
const inner = `inner ${name}`;
const outer = `outer ${inner}`;
console.log(outer); // outer inner AliceNested template literals evaluate from inside out, allowing complex string composition.
Common Mistakes
Using Quotes Instead of Backticks
const failing = "Hello ${name}"; // ${name} won't interpolate
// Use backticks: \`Hello ${name}\`Template syntax only works with backticks, not with single or double quotes.
Forgetting to Escape Backticks
const text = `This is a `quote`; // escape backtick with `Backticks inside template literals must be escaped with `.
Best Practices
Prefer Template Literals for Readability
const msg = `User: ${user.name}, Role: ${user.role}`;Template literals improve readability compared to concatenation, especially with multiple variables.
Use Tags for Sanitization and Localization
// tag functions help apply localization or escape
const localized = i18n`Welcome, ${user}`;Tagged templates are ideal for processing dynamic content before rendering.
Related Topics
Key Takeaways
- Use backticks to create template literals
- Embed variables and expressions with ${...}
- Template literals support multi-line strings naturally
- Tagged templates let you preprocess strings (e.g. for escaping)
- `String.raw` returns raw, uninterpreted text
- Prefer template literals over concatenation for readability