Template Literals

Updated · 6 min read
easyES2026javascriptstringstemplate-literalses6

A template literal is a string written between backticks (`) that can contain placeholders, ${expression}, whose values are inserted into the text. Template literals can also span several lines. Introduced in ES2015, they replaced most string joining with +, because the finished text is easy to see at a glance: `Fee for ${name}: $${fee}` reads almost exactly like the output.

In One Minute

  • Write them with backticks: `Hello, ${name}!`.
  • ${} accepts any expression: variables, math, function calls, ternaries.
  • Line breaks inside backticks are kept, so multi-line text needs no \n.
  • A tagged template (tag`text ${x}`) passes the pieces to a function, which can process them: escaping HTML, formatting currency, building queries.
  • String.raw`...` keeps backslashes as written.

Placeholders

Syntax

syntax.js
`text ${expression} more text`

The expression is evaluated, converted to a string, and inserted.

Example

placeholders.js▶ Try it
const name = "Srihitha";
const fee = 450;
const paid = 300;
 
console.log(`Student: ${name}`);
console.log(`Balance: $${fee - paid}`);
console.log(`Status: ${paid >= fee ? "Paid" : "Owes money"}`);
console.log(`Name in capitals: ${name.toUpperCase()}`);
console.log(`Fees: ${[120, 85, 45]}`);
Output
Student: Srihitha
Balance: $150
Status: Owes money
Name in capitals: SRIHITHA
Fees: 120,85,45

Explanation: in $${fee - paid}, the first $ is a literal dollar sign, and ${...} is the placeholder. Any expression works inside, including a ternary or a method call. An array is converted with its default toString, which joins the items with commas and no spaces; use .join(", ") inside the placeholder for nicer output.

Multi-Line Strings

Everything between the backticks is kept, including line breaks and indentation:

multiline.js▶ Try it
const name = "Advitha";
const receipt = `Receipt
Student: ${name}
Amount:  $95
Thank you!`;
 
console.log(receipt);
Output
Receipt
Student: Advitha
Amount:  $95
Thank you!

Indentation inside the backticks is kept too, which can add unwanted spaces when the template sits inside an indented function. For text where exact spacing matters, build lines in an array and join("\n"), as the In Practice example does.

Expressions, Not Statements

${} takes an expression: anything that produces a value. Statements such as if or for aren't allowed inside, but their expression forms are:

Instead ofUse inside ${}
if...elseThe ternary: ${isPaid ? "Paid" : "Due"}
A loopAn array method: ${items.map((i) => i.name).join(", ")}
Several statementsA function call: ${formatFee(fee)}

Templates can also be nested, since a template literal is itself an expression:

nested.js▶ Try it
const students = [
  { name: "Navika", balance: 0 },
  { name: "Srihitha", balance: 120 },
];
 
const lines = students.map(
  (s) => `${s.name}: ${s.balance > 0 ? `$${s.balance} due` : "paid"}`
);
console.log(lines.join("\n"));
Output
Navika: paid
Srihitha: $120 due

Tagged Templates

A tagged template is a template literal with a function name in front of it. Instead of producing a string directly, JavaScript calls the function with two things: an array of the literal text pieces, and the values of the placeholders. The function returns whatever it wants.

tagged.js▶ Try it
function show(strings, ...values) {
  console.log(strings);
  console.log(values);
  return "done";
}
 
const name = "Navika";
const fee = 120;
const result = show`Fee for ${name} is ${fee}.`;
console.log(result);
Output
['Fee for ', ' is ', '.']
['Navika', 120]
done

Explanation: the text is split around the placeholders into three pieces, and the two placeholder values are passed separately. There is always one more string than there are values. The ...values syntax collects the remaining arguments into an array; it is the rest parameter, covered in the function parameters lesson.

A real tag interleaves the pieces back together while processing each value. This one formats numbers as US dollars:

usd-tag.js▶ Try it
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
 
function usd(strings, ...values) {
  return strings.reduce((out, text, i) => {
    const value = i < values.length ? values[i] : "";
    return out + text + (typeof value === "number" ? money.format(value) : value);
  }, "");
}
 
const name = "Advitha";
console.log(usd`${name} paid ${95} of ${1234.5}.`);
Output
Advitha paid $95.00 of $1,234.50.

Libraries use tags for safe HTML (escaping each value so it can't inject markup), SQL queries (turning values into safe parameters), CSS-in-JS and translations.

String.raw

String.raw is a built-in tag that ignores escape sequences, keeping backslashes exactly as typed. It is handy for Windows paths and regular expressions:

raw.js▶ Try it
console.log(`C:\new\data`);
console.log(String.raw`C:\new\data`);
Output
C:
ewdata
C:\new\data

Explanation: in the first line, \n became a new line and \d became a plain d, so both backslashes were lost. String.raw kept them as plain text.

In Practice

The Fee Tracker prints a receipt. Each line is a template literal; the lines are joined so the indentation of the code doesn't leak into the text:

receipt.js▶ Try it
function receipt(student, payments) {
  const total = payments.reduce((sum, p) => sum + p.amount, 0);
  const lines = [
    `Receipt for ${student.name}`,
    ...payments.map((p) => `  ${p.date}  $${p.amount.toFixed(2)}`),
    `Total paid: $${total.toFixed(2)}`,
    `Balance:    $${(student.fee - total).toFixed(2)}`,
  ];
  return lines.join("\n");
}
 
console.log(receipt(
  { name: "Srihitha Anamaneni", fee: 450 },
  [{ date: "01/05/2026", amount: 200 }, { date: "02/05/2026", amount: 150 }]
));
Output
Receipt for Srihitha Anamaneni
  01/05/2026  $200.00
  02/05/2026  $150.00
Total paid: $350.00
Balance:    $100.00

Common Mistakes

Using normal quotes with ${}. "Hi ${name}" prints the characters ${name} literally. Placeholders only work in backticks.

Inserting user input into HTML with a template. el.innerHTML = `<b>${name}</b>` lets a malicious name inject markup. Use textContent, or a tag that escapes values; the DOM chapter explains this.

Forgetting the literal $ for prices. `${fee}` gives 120; `$${fee}` gives $120.

Unwanted indentation in multi-line templates. Spaces before each line are part of the string. Join an array of lines instead.

Practice

Challenge: Write feeLine(name, amount, isLate) that returns "Navika: $120.00" and appends " (late)" only when isLate is true, using one template literal with a ternary inside it.

Show solution
fee-line.js▶ Try it
function feeLine(name, amount, isLate) {
  return `${name}: $${amount.toFixed(2)}${isLate ? " (late)" : ""}`;
}
 
console.log(feeLine("Navika", 120, false));
console.log(feeLine("Advitha", 95.5, true));
Output
Navika: $120.00
Advitha: $95.50 (late)

Quick check: Template literals

3 questions
1What does "Total: ${fee}" (with double quotes) print?
2Which can go inside ${}?
3In a tagged template with two placeholders, how many literal strings does the tag receive?

Key Takeaways

NeedWrite
Insert a value`Hi ${name}`
A price`$${fee.toFixed(2)}`
A choice`${ok ? "Yes" : "No"}`
A list`${items.join(", ")}`
Keep backslashesString.raw`C:\dir`

Was this tutorial helpful?

Lesson 20 of 139