Template Strings in JavaScript
Introduction
Template literals (template strings) use backticks ` and let you embed expressions, build multi-line text, and tag strings for advanced formatting. They replace awkward quote concatenation in most modern code. This chapter focuses on everyday patterns you will use in logs, UI copy, and API messages.
Prerequisites
Basic Interpolation
Wrap expressions in ${ ... } inside backticks:
// Embed variables in a sentence
const product = "Notebook";
const qty = 2;
const line = `You ordered ${qty} x ${product}.`;
console.log(line);Any expression is allowed inside ${}:
// Expression inside interpolation
const price = 6.5;
console.log(`Total: $${(price * 3).toFixed(2)}`);Multi-Line Strings
Backticks preserve line breaks without \n escapes:
// Multi-line email draft
const name = "Sam";
const body = `Hi ${name},
Thanks for joining our course.
We are glad you are here.
— The team`;
console.log(body);Nesting and Readability
Keep nested templates simple—deep nesting hurts readability:
// Small nested template for status badge
const score = 92;
const grade = score >= 90 ? "A" : "B";
const report = `Score: ${score} (${grade})`;
console.log(report);Escaping Backticks
If you need a literal backtick inside a template, escape it:
// Escape backtick inside template literal
const tip = `Use \`const\` by default.`;
console.log(tip);Tagged Templates (Preview)
A tag function processes template parts for advanced formatting (styled components, i18n, safe HTML):
// Simple tag function (educational)
function upper(strings, ...values) {
return strings.reduce((result, part, i) => {
const value = values[i] ?? "";
return result + part + String(value).toUpperCase();
}, "");
}
const user = "ada";
console.log(upper`Hello, ${user}!`);You rarely write tags on day one—know they exist when libraries mention “tagged templates.”
Template Strings vs Regular Strings
| Task | Regular string | Template literal |
|---|---|---|
| Variables in text | "Hi " + name | `Hi ${name}` |
| Multi-line | \n escapes | Natural line breaks |
| Expression math | Concatenate pieces | ${price * 2} |
Mini Example: Invoice Line Items
// Build a short invoice block for the console
const items = [
{ name: "Sticker", price: 3 },
{ name: "Mug", price: 12 },
];
let output = "Invoice\n--------\n";
for (const item of items) {
output += `${item.name.padEnd(10)} $${item.price.toFixed(2)}\n`;
}
const total = items.reduce((sum, item) => sum + item.price, 0);
output += `--------\nTotal: $${total.toFixed(2)}`;
console.log(output);FAQ
Can I use template literals in older browsers?
Evergreen browsers and current Node.js support them (ES2015+). This course assumes modern runtimes.
Are template literals the same as Python f-strings?
Very similar idea: interpolate expressions inside string syntax.
Does ${} evaluate arbitrary code?
Yes—keep expressions simple. Heavy logic belongs outside the template.