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.
- 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 => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[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><img src=x onerror="alert(1)"></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
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.