Template Literals & Tagged Templates

Published by Brayan K

A template literal is a string written with backticks that can embed live expressions with ${...}, span multiple lines, and be processed by a tag function — replacing clumsy string concatenation entirely.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Build the message when the statement executes

The expressions in a template are evaluated when JavaScript constructs that value. “Live” in the introduction means actual expressions can be evaluated, not that a saved message automatically updates whenever a variable changes. Start with a receipt whose quantity changes after the first message is created.

let quantity = 2;
const firstMessage = `Packing ${quantity} parcels`;
quantity = 5;
console.log(firstMessage);
console.log(`Packing ${quantity} parcels`);

// ✅ Expected output:
// Packing 2 parcels
// Packing 5 parcels

Both templates use the same expression, but they execute at different times. The first variable holds an already-built string. Create a new string, or call a formatting function again, when the displayed information must reflect a changed value.

function packingMessage(quantity, destination) {
  return `Packing ${quantity} parcels for ${destination}.`;
}
console.log(packingMessage(2, "North desk"));
console.log(packingMessage(5, "South desk"));

// ✅ Expected output:
// Packing 2 parcels for North desk.
// Packing 5 parcels for South desk.

This is the input/result contract from Functions applied to text. The function receives values and returns a message; its caller chooses when to ask for another message and where to display it.

Backticks enable placeholders; ordinary quotes preserve them

const destination = "North";
console.log("Desk: ${destination}");
console.log(`Desk: $destination`);
console.log(`Desk: ${destination}`);

// ✅ Expected output:
// Desk: ${destination}
// Desk: $destination
// Desk: North

An ordinary quoted string keeps the placeholder characters as text. A bare dollar sign inside a template also stays literal. Interpolation requires the dollar sign followed by braces, inside backtick delimiters.

An expression can be a name, a calculation or a function call. It must be valid at the point the template executes. If it reads an undeclared name, constructing the message fails before the surrounding console call receives a result.

console.log("Preparing message");
console.log(`Destination: ${destination}`);

// ✅ Expected output:
// Preparing message

// ✅ Expected error:
// ReferenceError: destination is not defined

Calculate inside the placeholder, not after a text prefix

const notebooks = 2;
const pens = 3;
console.log("Items: " + notebooks + pens);
console.log(`Items: ${notebooks + pens}`);

// ✅ Expected output:
// Items: 23
// Items: 5

The plus chain starts by joining a string to the first number, then joins the second number to the resulting text. The template version first evaluates the addition inside the placeholder, then inserts its result. The expression is not interpreted as part of the surrounding English sentence.

const quantityText = "2";
console.log(`Items: ${quantityText + 3}`);
console.log(`Items: ${Number(quantityText) + 3}`);

// ✅ Expected output:
// Items: 23
// Items: 5

Backticks do not repair incorrect input types. If an expression performs string concatenation, interpolation inserts that concatenated result. Type Coercion (== vs ===) owns conversion behavior; decide and validate the intended type before formatting the result.

Whitespace belongs to the value

const quantity = 3;
const message = `Packing list:
  ${quantity} parcels
Ready`;
console.log(message);
console.log(JSON.stringify(message));

// ✅ Expected output:
// Packing list:
//   3 parcels
// Ready
// "Packing list:\n  3 parcels\nReady"

The source newline becomes a newline in the string, and the two spaces before the quantity remain. JSON.stringify exposes those boundaries in a single quoted representation. Indenting a template to match surrounding JavaScript can therefore indent the produced text too.

Use a multiline template when the line breaks are part of the required result. If they exist only to make the source look aligned, check the resulting whitespace before sending the text to a file, email or user interface. String trimming removes boundaries, not arbitrary indentation on every line.

Escape syntax only when you want it to remain literal

const quantity = 3;
console.log(`Use \` around a template.`);
console.log(`Literal placeholder: \${quantity}`);
console.log(`Actual quantity: ${quantity}`);

// ✅ Expected output:
// Use ` around a template.
// Literal placeholder: ${quantity}
// Actual quantity: 3

The backslash before a backtick keeps it from ending the template. The backslash before the dollar sign prevents that placeholder from being evaluated. The escape is source syntax; the backslash used for escaping is not printed in these results.

Inserted text is not parsed again as JavaScript. If a value itself contains placeholder-looking characters, interpolation treats those characters as data. This is useful when explaining code, but it is not a general safety guarantee for wherever the final text is used.

const note = "Quantity is ${quantity}";
const quantity = 3;
console.log(`Note: ${note}`);

// ✅ Expected output:
// Note: Quantity is ${quantity}

String.raw preserves escapes, not the old value of an expression

const quantity = 3;
const cooked = `line\nquantity: ${quantity}`;
const raw = String.raw`line\nquantity: ${quantity}`;
console.log(JSON.stringify(cooked));
console.log(JSON.stringify(raw));

// ✅ Expected output:
// "line\nquantity: 3"
// "line\\nquantity: 3"

The ordinary template interprets the newline escape. String.raw preserves the backslash and the letter n from the literal segment. Its placeholder is still evaluated and inserted. “Raw” does not mean “do not substitute variables,” and it does not mean “safe for HTML or a database.”

A tag receives the pieces and the original values

function inspectParts(parts, quantity, destination) {
  console.log(JSON.stringify(parts));
  console.log(typeof quantity);
  console.log(typeof destination);
  return "Inspection finished";
}
console.log(inspectParts`Pack ${3} for ${"North"}.`);

// ✅ Expected output:
// ["Pack "," for ","."]
// number
// string
// Inspection finished

Putting a function name directly before the backtick calls it as a tag. The first argument is an array of literal string segments; subsequent arguments are the evaluated substitutions, still with their own types. Two substitutions produce three literal segments, including any empty segments at the ends.

This example uses a fixed number of parameters to expose the calling convention. A general tag needs to handle its allowed number of substitutions explicitly. Arrays and Objects owns array operations rather than repeating their full catalog here.

function calculate(parts, quantity, unitPrice) {
  return quantity * unitPrice;
}
const result = calculate`${3} at ${4}`;
console.log(result);
console.log(typeof result);

// ✅ Expected output:
// 12
// number

The result is whatever the tag returns; it need not be a string. A tag is not automatically a formatter, validator or escape function. Those behaviors must actually be implemented by that tag.

Formatting text does not decide how safely it will be used

const suppliedName = "<em>Rae</em>";
const message = `Hello, ${suppliedName}`;
console.log(message);

// ✅ Expected output:
// Hello, <em>Rae</em>

This program only logs a string. If a later operation interprets that string as HTML, the same characters have a different meaning. Backticks did not escape them. For plain text in a webpage, use a text-writing operation such as textContent; DOM Manipulation owns choosing and updating elements.

Likewise, interpolating a value into a SQL-looking string does not bind it as a database parameter. Use the parameter API of the database library. A particular tag library may provide safe binding, but the JavaScript tag syntax alone provides no such behavior.

Complete a dispatch message

Fill the two expressions inside the template. Keep the delimiters and placeholder braces already provided.

const destination = "North";
const boxes = 3;
// 👉 replace ___ with destination
// 👉 replace ___ with boxes * 2
const message = `Send to ${___}: ${___} labels`;
console.log(message);

// ✅ Expected output:
// Send to North: 6 labels

Write an invoice formatter with a stable layout

Write invoice(customer, quantity, unitPrice). It should return three lines: the customer label and name, the quantity label and value, then the total label and calculated quantity times unit price. Use one template and no indentation inside the returned text. Call it for Rae buying three items at four units each, and print the returned invoice.

function invoice(customer, quantity, unitPrice) {
  return `Customer: ${customer}
Quantity: ${quantity}
Total: ${quantity * unitPrice}`;
}
console.log(invoice("Rae", 3, 4));

// ✅ Expected output:
// Customer: Rae
// Quantity: 3
// Total: 12

Check line breaks as well as the arithmetic. Then call the function with a different quantity; do not expect a previously returned invoice string to update itself. This exercise formats supplied numeric inputs. A production invoice would also need explicit validation, currency rules and a suitable money representation.

Reference: MDN’s template literal and tagged template reference.

Practice quiz

What does this complete program print? const name = "Rae"; console.log("Hello ${name}");

  • Hello ${name}
  • Hello Rae
  • ReferenceError: name is not defined
  • undefined

Answer: Hello ${name}. Ordinary quotes preserve the placeholder text.

What does this complete program print? let count = 2; const message = `Count: ${count}`; count = 5; console.log(message);

  • Count: 5
  • Count: 2
  • Count: count
  • undefined

Answer: Count: 2. The string was built while count held the earlier value.

What does this complete program print? console.log(`Total: ${2 + 3}`);

  • Total: 23
  • Total: 2 + 3
  • Total: 5
  • 5

Answer: Total: 5. The expression is evaluated first, then its result is inserted.

What does this complete program print? const count = 3; console.log(`Count: \${count}`);

  • Count: 3
  • Count: \3
  • ReferenceError
  • Count: ${count}

Answer: Count: ${count}. Escaping the dollar sign preserves the placeholder characters.

What does this complete program print? const note = "${count}"; const count = 3; console.log(`Note: ${note}`);

  • Note: ${count}
  • Note: 3
  • ReferenceError
  • Note: undefined

Answer: Note: ${count}. Interpolated string data is not recursively evaluated as template syntax.

What does this complete program print? const count = 3; console.log(JSON.stringify(String.raw`x ${count}`));

  • "x 3"
  • "x\ 3"
  • "x3"
  • "x\ ${count}"

Answer: "x\ 3". String.raw preserves the literal escape while still evaluating the substitution.

What does this complete program print? function inspect(parts, value) { return typeof value; } console.log(inspect`Value: ${4}`);

  • string
  • 4
  • number
  • Value: 4

Answer: number. A tag receives the original substituted value; it has not automatically become a string.

What does this complete program print? function total(parts, left, right) { return left + right; } const result = total`${2} and ${3}`; console.log(typeof result);

  • string
  • object
  • undefined
  • number

Answer: number. The tag returns a number, so the tagged expression also has a numeric result.

Continue this course

Related lessons