1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Template Literals: 10 Examples Including Tagged Templates

JavaScript template literals use backticks to build strings with embedded expressions, multiple lines and custom processing. Learn interpolation, multiline text, nesting, escaping, String.raw and tagged templates for safe HTML and SQL, with every example run in Node.js.

9 min read
JavaScript template literals: 10 examples including tagged templates

Key takeaways

  • JavaScript template literals are strings in backticks that can embed any expression with ${...}.
  • They keep line breaks and indentation exactly as typed, which helps and sometimes hurts.
  • A tagged template passes the text and values to a function, which can escape HTML, parameterise SQL or format currency.
  • Interpolating user input into HTML without a safe tag is an XSS risk; our test shows the difference.

Before ES2015, building strings in JavaScript meant chains of + signs, missing spaces and awkward \n escapes. JavaScript template literals replaced all of that with one readable syntax, and added a powerful extra: tags, functions that process a template before it becomes a string. Libraries for CSS-in-JS, GraphQL queries, HTML rendering and SQL all build on them.

We ran every example with Node.js v24.22.1, and the output is shown as printed. Template literals work the same way in all modern browsers. New to the language? Start with our JavaScript tutorial for beginners.

What are template literals?

A template literal is a string written between backtick characters instead of single or double quotes. Inside it, ${expression} inserts the value of any JavaScript expression, and line breaks are kept as part of the string. They were called “template strings” in early drafts of the spec, so you will see both names.

Example 1: basic interpolation

const name = "Asha", items = 3, price = 49.5;

console.log(`Hi ${name}, you have ${items} items costing ${(items * price).toFixed(2)}`);
// Hi Asha, you have 3 items costing 148.50

console.log("Hi " + name + ", you have " + items + " items");
// Hi Asha, you have 3 items

The template version reads like the final sentence, with values dropped into place. The concatenated version needs careful spacing around every +, which is where typos creep in.

Example 2: any expression works

console.log(`Status: ${items > 0 ? "in cart" : "empty"}`);
// Status: in cart

console.log(`Total: ${[1, 2, 3].map(n => n * 2).join(", ")}`);
// Total: 2, 4, 6

Ternaries, function calls, method chains and arithmetic are all allowed. Statements such as if or for are not, because the placeholder must produce a value. Keep the logic short; if a placeholder needs more than one line, compute it first in a well-named variable. For the array methods used here, see our array methods guide.

Example 3: multiline strings

const multi = `Line one
  Line two (indented)`;
console.log(JSON.stringify(multi));
// "Line one\n  Line two (indented)"

The line break and the two spaces of indentation became part of the string. That is great for email bodies, SQL and HTML snippets, but it also means that indenting a template to match your code adds real spaces to the output. We fix that in the indentation section below.

Example 4: how values are converted

console.log(`obj: ${{ a: 1 }} | arr: ${[1, [2, 3]]} | null: ${null} | undef: ${undefined}`);
// obj: [object Object] | arr: 1,2,3 | null: null | undef: undefined

Every value goes through string conversion. Objects become [object Object], arrays are joined with commas (nested arrays are flattened into the same list), and null and undefined appear as words. Seeing “undefined” or “[object Object]” in a UI is a sure sign of a missing property or a forgotten JSON.stringify.

Example 5: nesting templates

console.log(`nested: ${`inner ${1 + 1}`}`);
// nested: inner 2

A placeholder can contain another template literal. This is handy for conditional fragments, such as ${isAdmin ? `Admin: ${name}` : ""}, or for mapping an array to HTML rows. Beyond one level of nesting, readability drops quickly, so pull inner templates into small helper functions.

Example 6: escaping backticks and dollar signs

console.log(`backtick \` and dollar \${not} interpolated`);
// backtick ` and dollar ${not} interpolated

console.log('single quotes: literal', '${x}');
// single quotes: literal ${x}

Use a backslash to include a literal backtick or to stop ${ from starting a placeholder. A plain $ not followed by { needs no escape. Also note the second line: in a normal single-quoted string, ${x} is just text. Writing a template with the wrong quotes is a frequent beginner bug, and it fails silently.

Example 7: tagged templates

Put a function name directly before a template and JavaScript calls that function instead of building the string. The function receives an array of the literal text parts and then each value:

function tag(strings, ...values) {
  return JSON.stringify({ strings, values, raw: strings.raw });
}
console.log(tag`a${1}b${2}c`);
// {"strings":["a","b","c"],"values":[1,2],"raw":["a","b","c"]}

There is always one more string part than values, because the text before the first placeholder and after the last one are both included, even if empty. The tag can return anything: a string, an object or even a function. That is the hook that lets libraries turn templates into small domain-specific languages.

Example 8: a tag that prevents XSS

const esc = s => String(s).replace(/[&<>"']/g, c => ({
  "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));

function html(strings, ...vals) {
  return strings.reduce((out, s, i) => out + s + (i < vals.length ? esc(vals[i]) : ""), "");
}

const userInput = '<img src=x onerror="alert(1)">';
console.log(`<p>${userInput}</p>`);
// <p><img src=x onerror="alert(1)"></p>
console.log(html`<p>${userInput}</p>`);
// <p>&lt;img src=x onerror=&quot;alert(1)&quot;&gt;</p>

The plain template inserted a working script injection into the HTML. The tagged version escaped only the values, leaving the trusted template text untouched, so the payload is displayed as harmless text. A tag is only as safe as its escaping rules, though: this simple version handles element content, not URLs or inline scripts. In production use a maintained library or framework rendering. The fold uses reduce to stitch the parts together.

Example 9: a tag for parameterised SQL

function sql(strings, ...vals) {
  return { text: strings.reduce((q, s, i) => q + "$" + i + s), values: vals };
}
const id = "1 OR 1=1";
console.log(sql`SELECT * FROM users WHERE id = ${id} AND role = ${"admin"}`);
// { text: 'SELECT * FROM users WHERE id = $1 AND role = $2',
//   values: [ '1 OR 1=1', 'admin' ] }

Instead of pasting the hostile 1 OR 1=1 into the query, the tag replaced each value with a numbered placeholder and returned the values separately, which is the shape PostgreSQL drivers expect for parameterised queries. Several popular Node.js database libraries use this exact idea. We printed the object but did not send it to a database.

Tip: never build SQL or HTML by plain interpolation of user input. Use a tag or library that separates trusted text from untrusted values.

Example 10: String.raw for backslashes

console.log(String.raw`C:\new\table ${1 + 1}`);
// C:\new\table 2
console.log("C:\new\table".length, String.raw`C:\new\table`.length);
// 10 12

In a normal string, \n and \t become a newline and a tab, so the Windows path shrank to 10 characters. String.raw is a built-in tag that keeps backslashes as typed while still interpolating placeholders. It is useful for file paths, regex sources and LaTeX. Every tag can read the same raw text through strings.raw, as example 7 showed: for tag`\n${0}` the cooked string held a real newline while the raw one held a backslash followed by the letter n.

Formatting values with a tag

const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
const currency = (s, ...v) =>
  s.reduce((o, str, i) => o + str + (i < v.length ? inr.format(v[i]) : ""), "");

console.log(currency`Order total ${1234.5} incl. tax ${98}`);
// Order total ₹1,234.50 incl. tax ₹98.00

A tag can apply consistent formatting to every value, so templates stay readable while numbers, dates or units follow your locale rules. The same approach powers translation helpers that look up the text parts in a dictionary.

Dealing with indentation

const dedent = s => s.replace(/^\n/, "").replace(/^ +/gm, "");
console.log(JSON.stringify(dedent(`
    SELECT id
    FROM t`)));
// "SELECT id\nFROM t"

A small dedent helper removes the leading newline and indentation that come from formatting your code nicely. This simple version strips all leading spaces from every line; npm packages offer smarter versions that keep relative indentation.

Performance: templates vs concatenation

We built one million short strings each way in Node.js 24 and kept the best of five runs, measuring each twice in alternating order:

Approach Run 1 Run 2
`${name}-${i}` 62.8 ms 69.3 ms
name + "-" + i 86.6 ms 82.5 ms

Template literals were not slower; in this test they were a little faster. Micro-benchmarks like this shift between engine versions, so the practical conclusion is simply that speed is no reason to avoid them. Choose by readability.

Common mistakes

  • Using quotes instead of backticks, so ${name} prints literally.
  • Indenting multiline templates and shipping unwanted spaces.
  • Interpolating objects and getting [object Object].
  • Inserting user input into HTML or SQL without escaping or parameters.
  • Packing complex logic into placeholders instead of variables.
  • Forgetting that tags receive one more string part than values.

Final thoughts

JavaScript template literals make strings readable: embed expressions with ${}, write multiline text naturally, and escape the rare backtick or dollar sign. Tagged templates go further, turning a template into input for a function that can escape HTML, parameterise SQL, format currency or keep raw backslashes. Use plain templates for everyday strings and a trusted tag whenever untrusted data meets HTML or SQL. Pair them with destructuring for clean, expressive code.

Frequently asked questions

What is a template literal in JavaScript?

It is a string written in backticks instead of quotes. It can embed expressions with a dollar sign and curly braces and can span multiple lines without escape characters.

What is a tagged template in JavaScript?

It is a template literal preceded by a function name. JavaScript calls that function with the text parts and the embedded values, and the function decides what to return.

How do I write a backtick inside a template literal?

Escape it with a backslash. To show a dollar sign followed by a curly brace without interpolation, escape the dollar sign with a backslash as well.

Are template literals slower than string concatenation?

No meaningful difference. In our Node.js 24 test, building a million strings took about 63 to 69 ms with templates and 83 to 87 ms with concatenation.

Do template literals prevent XSS?

No. Plain template literals insert values as they are. Only a tag function or framework that escapes the values makes HTML output safe.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
Software Development

HTTP Cookies Explained: Secure, HttpOnly, SameSite and Scope

HTTP cookies explained: Set-Cookie, Path, Domain, expiry, Secure, HttpOnly, SameSite, prefixes, deleting cookies and a secure session recipe, tested locally.

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Databases & SQL

SQL Auto Increment: MySQL, PostgreSQL, SQL Server and SQLite

SQL auto increment in MySQL, PostgreSQL, SQL Server and SQLite: syntax, reading the new ID, why gaps appear, ID reuse,…

Read article →
Databases & SQL

SQL BETWEEN: Inclusive Ranges and the Date Trap Explained

SQL BETWEEN explained with tested queries: inclusive ranges, reversed bounds, NULLs, the last-day date trap, half-open ranges and index-friendly date…

Read article →
Software Development

JavaScript Template Literals: 10 Examples Including Tagged Templates

JavaScript template literals explained with 10 tested examples: interpolation, multiline strings, escaping, tagged templates for safe HTML and SQL, and…

Read article →
Software Development

Python heapq: Priority Queues, Top N and Heaps Explained

Python heapq explained: heappush, heappop, heapify, priority queues with tie-breakers, max heaps, nlargest and merge, with real timings against sorting.

Read article →
Software Development

Python Walrus Operator (:=) Explained With 8 Real Examples

The Python walrus operator := explained with 8 tested examples: if checks, regex matches, while loops, comprehensions, scope rules, precedence…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
Software Development

CORS Explained: Preflight Requests, Headers and How to Fix CORS Errors

CORS explained: origins, simple and preflight requests, the response headers your server must send, credentials, and how to fix common…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Databases & SQL

SQL CAST Explained: Convert Data Types With Tested Examples

SQL CAST explained with tested examples: text to number, truncation, integer division, numbers stored as text, dates, bad input and…

Read article →
Databases & SQL

SQL DISTINCT: How to Remove Duplicate Rows (and Its Traps)

SQL DISTINCT explained with tested queries: one and many columns, NULLs, COUNT DISTINCT, DISTINCT vs GROUP BY, the SUM DISTINCT…

Read article →
Software Development

JavaScript Reduce Explained: 12 Practical Examples

JavaScript reduce explained step by step with 12 practical examples: sums, tallies, grouping, Maps, pipelines, sequential promises and the empty…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Software Testing

State Transition Testing: Diagram, Table and Example

State transition testing explained with a login lockout example: states, events, the diagram, the state table, valid and invalid transitions,…

Read article →
Databases & SQL

Second Highest Salary in SQL: 5 Tested Ways and the Tie Trap

Find the second highest salary in SQL five ways: MAX subquery, LIMIT OFFSET, DENSE_RANK, a correlated subquery and per department,…

Read article →
Databases & SQL

SQL ROW_NUMBER: Top N per Group, Dedupe and Pagination

SQL ROW_NUMBER explained with tested queries: PARTITION BY, top N per group, deleting duplicates, pagination, the tie trap and how…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →
Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →