JavaScript Template Literals: Interpolation, Multi-Line Strings and Tagged Templates
Joining text with + quickly becomes hard to read: "Order " + id + " for " + name + " costs ₹" + total. Template literals, written with back-ticks, let you put values straight into a string with ${...}, write strings over several lines, and even process strings with a custom function (tagged templates). In this lesson you will use them to build messages, URLs, test data and reports, and learn the pitfalls such as printing [object Object] or unsafe values.
📖 What You’ll Learn: template literal syntax, interpolation with ${}, expressions and function calls inside placeholders, multi-line strings and indentation, nested templates, formatting values (numbers, dates, objects), building URLs and file names safely, String.raw, tagged templates, and practical uses in test automation.
🔤 Template Literal Syntax
Definition: a template literal is a string written between back-ticks `...`. It can contain placeholders ${expression} whose values are converted to strings and inserted. This is called string interpolation.
📄 syntax.js
const name = "Asha";
const passed = 18;
const total = 20;
const oldWay = "Hi " + name + ", " + passed + " of " + total + " tests passed.";
const newWay = `Hi ${name}, ${passed} of ${total} tests passed.`;
console.log(oldWay);
console.log(newWay);
console.log(oldWay === newWay);
⌨️ Terminal
node syntax.js
🖥️ Output
Hi Asha, 18 of 20 tests passed.
Hi Asha, 18 of 20 tests passed.
true
💡 Tip: The back-tick key is usually at the top left of the keyboard, below Esc. Template literals were added in ES2015 and work everywhere today.
🧮 Expressions Inside ${}
A placeholder accepts any expression: arithmetic, function calls, ternaries, property access, method calls. It does not accept statements such as if or for.
📄 expressions.js
const price = 249.5;
const qty = 3;
const user = { name: "Ravi", isPremium: true };
console.log(`Subtotal: ₹${price * qty}`);
console.log(`Total with tax: ₹${(price * qty * 1.18).toFixed(2)}`);
console.log(`Customer: ${user.name.toUpperCase()}`);
console.log(`Shipping: ${user.isPremium ? "free" : "₹49"}`);
console.log(`Items: ${["pen", "book"].join(", ")}`);
console.log(`Pass rate: ${Math.round((18 / 20) * 100)}%`);
⌨️ Terminal
node expressions.js
🖥️ Output
Subtotal: ₹748.5
Total with tax: ₹883.23
Customer: RAVI
Shipping: free
Items: pen, book
Pass rate: 90%
Keep placeholders short. If an expression gets long, calculate it in a variable first and put only the variable in the template.
📄 Multi-Line Strings
Line breaks inside back-ticks are kept exactly, so you no longer need \n for multi-line text:
📄 multiline.js
const report = `Test Run Summary
----------------
Passed: 18
Failed: 2
Skipped: 1`;
console.log(report);
console.log(report.split("\n").length, "lines");
⌨️ Terminal
node multiline.js
🖥️ Output
Test Run Summary
----------------
Passed: 18
Failed: 2
Skipped: 1
5 lines
⚠️ Watch out: The indentation inside the back-ticks is part of the string. If you indent a template literal to match the surrounding code, those spaces appear in the output. Start the lines at the left margin, or remove the indentation afterwards.
📄 indent.js
function emailBody(name) {
return `
Hello ${name},
Your test run has finished.
`;
}
console.log(JSON.stringify(emailBody("Asha")));
const dedent = (text) => text.trim().split("\n").map((line) => line.trim()).join("\n");
console.log(dedent(emailBody("Asha")));
⌨️ Terminal
node indent.js
🖥️ Output
"\n Hello Asha,\n Your test run has finished.\n "
Hello Asha,
Your test run has finished.
🎨 Formatting Values in Templates
Every placeholder value is converted with String(). That is fine for strings and numbers, but objects and some values need formatting first:
📄 formatting.js
const order = { id: 451, items: 2 };
const missing = undefined;
const tags = ["smoke", "p1"];
console.log(`Order: ${order}`); // [object Object]
console.log(`Order: ${JSON.stringify(order)}`); // readable
console.log(`Coupon: ${missing}`); // "undefined" in the text
console.log(`Coupon: ${missing ?? "none"}`); // default
console.log(`Tags: ${tags}`); // arrays join with commas
console.log(`Price: ${(1299.5).toLocaleString("en-IN", { style: "currency", currency: "INR" })}`);
console.log(`Date: ${new Date(Date.UTC(2026, 10, 23)).toISOString().slice(0, 10)}`);
⌨️ Terminal
node formatting.js
🖥️ Output
Order: [object Object]
Order: {"id":451,"items":2}
Coupon: undefined
Coupon: none
Tags: smoke,p1
Price: ₹1,299.50
Date: 2026-11-23
⚠️ Watch out: Seeing [object Object] or undefined in a log, file name or error message means a placeholder received an object or a missing value. Use JSON.stringify for objects and ?? for possibly missing values.
🪆 Nesting Templates and Building Lists
A placeholder can contain another template literal. Combined with map and join, this builds lists and tables from arrays:
📄 nested.js
const results = [
{ test: "login", status: "passed", ms: 820 },
{ test: "search", status: "failed", ms: 1430 },
{ test: "cart", status: "passed", ms: 610 },
];
const lines = results
.map((r) => `${r.status === "passed" ? "✅" : "❌"} ${r.test.padEnd(8)} ${String(r.ms).padStart(5)} ms`)
.join("\n");
console.log(`Results (${results.length} tests)
${lines}
Failures: ${results.filter((r) => r.status === "failed").map((r) => r.test).join(", ") || "none"}`);
⌨️ Terminal
node nested.js
🖥️ Output
Results (3 tests)
✅ login 820 ms
❌ search 1430 ms
✅ cart 610 ms
Failures: search
The same technique builds simple HTML snippets, Markdown summaries for CI comments, or Slack messages.
🔗 Building URLs, Paths and File Names
Template literals are perfect for URLs, but user-supplied values must be encoded so spaces and special characters do not break the URL:
📄 urls.js
const baseURL = "https://qa.example.com";
const term = "usb cable & charger";
const page = 2;
console.log(`${baseURL}/search?q=${term}&page=${page}`); // broken URL
console.log(`${baseURL}/search?q=${encodeURIComponent(term)}&page=${page}`); // safe
const params = new URLSearchParams({ q: term, page: String(page) });
console.log(`${baseURL}/search?${params}`);
const testName = "Checkout: pay with UPI";
const stamp = "2026-11-23T10-30-00";
const fileName = `${testName.toLowerCase().replace(/[^a-z0-9]+/g, "-")}-${stamp}.png`;
console.log(fileName);
⌨️ Terminal
node urls.js
🖥️ Output
https://qa.example.com/search?q=usb cable & charger&page=2
https://qa.example.com/search?q=usb%20cable%20%26%20charger&page=2
https://qa.example.com/search?q=usb+cable+%26+charger&page=2
checkout-pay-with-upi-2026-11-23T10-30-00.png
⚠️ Watch out: Never build SQL queries, shell commands or HTML from user input with template literals. Values containing quotes or tags can change the meaning (SQL injection, XSS). Use parameterised queries, argument arrays and proper escaping.
📐 String.raw: Keep Backslashes
In a normal template literal, \n becomes a line break and \\ becomes one backslash. String.raw keeps the backslashes exactly as written, which is handy for Windows paths and regular expression source text:
📄 raw.js
console.log(`C:\\tests\\new`); // escapes are processed
console.log(String.raw`C:\tests\new`); // kept as written
console.log(String.raw`\d+\.\d{2}`); // regex source, readable
console.log(new RegExp(String.raw`^\d+\.\d{2}$`).test("19.99"));
⌨️ Terminal
node raw.js
🖥️ Output
C:\tests\new
C:\tests\new
\d+\.\d{2}
true
🏷️ Tagged Templates
Definition: a tagged template is a template literal preceded by a function name: tag`text ${value}`. Instead of producing a string directly, JavaScript calls the function with the literal text parts as an array and the placeholder values as further arguments. The function decides what to return.
📄 tag-basics.js
function inspect(strings, ...values) {
console.log("strings:", strings);
console.log("values:", values);
return "done";
}
const user = "Asha";
const count = 3;
console.log(inspect`User ${user} has ${count} open bugs`);
⌨️ Terminal
node tag-basics.js
🖥️ Output
strings: [ 'User ', ' has ', ' open bugs' ]
values: [ 'Asha', 3 ]
done
There is always one more string part than values. A tag can rebuild the string with changes, for example highlighting every value:
📄 tags.js
function highlight(strings, ...values) {
return strings.reduce((out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""), "");
}
const test = "login";
const ms = 1430;
console.log(highlight`Test ${test} took ${ms} ms`);
function currency(strings, ...values) {
const fmt = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
return strings.reduce((out, str, i) => out + str + (i < values.length ? fmt.format(values[i]) : ""), "");
}
console.log(currency`Subtotal ${1299.5}, tax ${233.91}`);
⌨️ Terminal
node tags.js
🖥️ Output
Test [login] took [1430] ms
Subtotal ₹1,299.50, tax ₹233.91
Libraries use tags for safe SQL (sql`SELECT * FROM users WHERE id = ${id}` sends id as a parameter), for GraphQL queries and for CSS-in-JS. You will mostly use tags rather than write them, but now you know how they work.
🧪 Tester Scenario: Generate Test Data and a Bug Report
📄 test-data.js
const runId = "nightly-1123";
const users = Array.from({ length: 3 }, (_, i) => ({
name: `Test User ${i + 1}`,
email: `qa+${runId}-${i + 1}@sqatools.in`,
password: `Pass@${1000 + i}`,
}));
console.table(users);
const failure = {
test: "checkout › pay with card",
expected: "Order confirmed",
actual: "Payment declined",
url: "https://qa.example.com/checkout/pay",
browser: "chromium",
};
const bugReport = `### Bug: ${failure.test}
**Environment:** QA, ${failure.browser}
**URL:** ${failure.url}
**Expected:** ${failure.expected}
**Actual:** ${failure.actual}
_Found by run ${runId}_`;
console.log(bugReport);
⌨️ Terminal
node test-data.js
🖥️ Output
┌─────────┬───────────────┬─────────────────────────────────┬─────────────┐
│ (index) │ name │ email │ password │
├─────────┼───────────────┼─────────────────────────────────┼─────────────┤
│ 0 │ 'Test User 1' │ 'qa+nightly-1123-1@sqatools.in' │ 'Pass@1000' │
│ 1 │ 'Test User 2' │ 'qa+nightly-1123-2@sqatools.in' │ 'Pass@1001' │
│ 2 │ 'Test User 3' │ 'qa+nightly-1123-3@sqatools.in' │ 'Pass@1002' │
└─────────┴───────────────┴─────────────────────────────────┴─────────────┘
### Bug: checkout › pay with card
**Environment:** QA, chromium
**URL:** https://qa.example.com/checkout/pay
**Expected:** Order confirmed
**Actual:** Payment declined
_Found by run nightly-1123_
Array.from({ length: 3 }, (_, i) => ...)creates three users, and template literals give each unique, predictable values.- The bug report is Markdown built with one multi-line template literal, ready to paste into Jira or a GitHub issue.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Rewrite with a template literal: "Hello " + first + " " + last + ", you have " + n + " messages", using first = “Asha”, last = “Rao”, n = 5.
Show answer
📄 practice1.js
const first = "Asha", last = "Rao", n = 5;
console.log(`Hello ${first} ${last}, you have ${n} messages`);🖥️ Output
Hello Asha Rao, you have 5 messagesQ2. Print 1 item or N items using a ternary inside a template literal, for counts 1 and 7.
Show answer
📄 practice2.js
for (const count of [1, 7]) {
console.log(`${count} item${count === 1 ? "" : "s"}`);
}🖥️ Output
1 item
7 itemsQ3. Build an API URL for user ID 42 with the query parameters include=orders and sort=date desc, making sure the space is encoded.
Show answer
📄 practice3.js
const id = 42;
const params = new URLSearchParams({ include: "orders", sort: "date desc" });
console.log(`https://api.example.com/users/${id}?${params}`);🖥️ Output
https://api.example.com/users/42?include=orders&sort=date+descURLSearchParams encodes the space as +, which is valid in query strings.
Q4. Print a three-line address using one template literal: name, street, city with PIN code.
Show answer
📄 practice4.js
const addr = { name: "Asha Rao", street: "12 MG Road", city: "Pune", pin: "411001" };
console.log(`${addr.name}
${addr.street}
${addr.city} - ${addr.pin}`);🖥️ Output
Asha Rao
12 MG Road
Pune - 411001Q5. Fix the output so it shows the object’s contents instead of [object Object].
const payload = { email: "qa@sqatools.in", role: "tester" };
console.log(`Sending ${payload}`);Show answer
📄 practice5.js
const payload = { email: "qa@sqatools.in", role: "tester" };
console.log(`Sending ${JSON.stringify(payload)}`);🖥️ Output
Sending {"email":"qa@sqatools.in","role":"tester"}Q6. Write a tag function upper that upper-cases every interpolated value but leaves the literal text unchanged.
Show answer
📄 practice6.js
function upper(strings, ...values) {
return strings.reduce((out, s, i) => out + s + (i < values.length ? String(values[i]).toUpperCase() : ""), "");
}
const env = "qa", browser = "firefox";
console.log(upper`Running on ${env} with ${browser}`);🖥️ Output
Running on QA with FIREFOX🧠 MCQ Quiz: Template Literals
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which characters delimit a template literal?Answer: Back-ticks `. Only back-tick strings support ${} and multi-line text.
- What does
`2 + 3 = ${2 + 3}`produce?Answer: “2 + 3 = 5”. Placeholders evaluate any expression. - What does
"Total: ${10}"(double quotes) produce?Answer: The literal text “Total: ${10}”. Interpolation only works in back-tick strings. - What appears for
`${{ a: 1 }}`?Answer: [object Object]. Objects are converted with String(); use JSON.stringify. - Can you put an if statement inside ${}?Answer: No, only expressions; use a ternary. if is a statement, not an expression.
- What does
String.raw`a\nb`return?Answer: The text a\nb with a backslash and n. String.raw keeps escape sequences as written. - In a tagged template with two placeholders, how many string parts does the tag receive?Answer: 3. There is always one more string part than values.
- Why use encodeURIComponent inside a URL template?Answer: So spaces and special characters do not break the URL. “&” in a value would otherwise start a new query parameter.
- What is printed?
const x = undefined; console.log(`Value: ${x ?? "n/a"}`);Answer: Value: n/a. ?? supplies the default for undefined. - Why can indentation be a problem in multi-line template literals?Answer: The spaces become part of the string. Everything between the back-ticks is kept.
💼 Interview Questions and Answers
Q1. What are template literals and what advantages do they have over string concatenation?
Template literals are back-tick strings (ES2015) that support ${expression} interpolation, real multi-line strings and tagged templates. Compared with + concatenation they are easier to read, avoid missing-space bugs, avoid accidental numeric addition versus string joining, and make multi-line text (reports, emails, Markdown) simple.
Q2. What is a tagged template, and where is it used in practice?
A tagged template calls a function with the literal string parts and the interpolated values separately: tag`a ${x} b` calls tag(["a ", " b"], x). The tag can escape, transform or reinterpret the values. Real uses: parameterised SQL (preventing injection), GraphQL query definitions, CSS-in-JS, internationalisation and String.raw.
Q3. Predict the output.
📄 predict.js
const a = 5, b = "5";
console.log(`${a + b}`, `${a}${b}`, `${a + Number(b)}`);
console.log(`${[1, 2, 3]}`, `${null}`, `${() => 1}`);
⌨️ Terminal
node predict.js
🖥️ Output
55 55 10
1,2,3 null () => 1
a + b joins a number and a string, giving “55”. Placeholders call String(), so the array becomes “1,2,3”, null becomes “null”, and a function becomes its source text.
Q4. Is it safe to build SQL or HTML with template literals?
Not with untrusted values. A plain template inserts values as-is, so `... WHERE name = '${input}'` allows SQL injection and `<div>${input}</div>` allows XSS. Use parameterised queries (or an SQL tag that sends parameters separately), and escape HTML or set textContent instead of innerHTML.
❓ Frequently Asked Questions
🤔 What is the difference between template literals and normal strings?
Template literals use back-ticks and support ${} interpolation, multi-line text and tags. Normal strings in single or double quotes do not.
🤔 How do I write a back-tick inside a template literal?
Escape it with a backslash: `Use \` for templates`. Use \${ to write a literal dollar-brace.
🤔 Are template literals slower than concatenation?
No meaningful difference. Choose them for readability.
🤔 Can template literals be used as object keys or in JSON?
They are just strings once evaluated, so obj[`key_${id}`] works. JSON itself must use double-quoted strings, but you can build JSON text with JSON.stringify.
🏁 Summary
- Template literals use back-ticks and insert values with
${expression}. - Placeholders accept any expression (maths, calls, ternaries), but not statements.
- Line breaks are kept, so multi-line text is easy; indentation is kept too.
- Format objects with
JSON.stringify, defaults with??, and URL values withencodeURIComponent/URLSearchParams. String.rawkeeps backslashes; tagged templates pass text parts and values to a function.
Next, continue with Lesson 27: Regular Expressions.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in