Template Literals and Tagged Templates in JavaScript
Template literals interpolate expressions and span lines, and a tag function receives the pieces separately. See escapes, String.raw and a safe SQL tag.

Template literals look like a nicer way to write strings, and for most code that is all they are. The feature with more reach is the one most people never use: a tag function that receives the fixed parts of the template and the interpolated values separately. That separation is what lets a library turn sql followed by a template into a safe parameterized query, or html into escaped markup, with no string concatenation in sight. This post covers the plain form first, then tags, String.raw and the security case. Examples run on Node.js 24. The string conversion rules are in how type coercion works, and template literals sit among the strings described in the post on UTF-16 strings.
What interpolation does
A template literal is delimited by backticks. Inside it, ${...} evaluates any expression and converts the result to a string.
const user = { name: "Ada", visits: 3 };
const tags = ["a", "b"];
console.log(`Hello ${user.name}, visit ${user.visits + 1}`);
console.log(`Tags: ${tags}`);
console.log(`Object: ${user}`);
console.log(`Nested: ${`inner ${1 + 1}`}`);
console.log(`Maybe: ${null} ${undefined} ${true}`);
console.log(`Line one
Line two`);Hello Ada, visit 4
Tags: a,b
Object: [object Object]
Nested: inner 2
Maybe: null undefined true
Line one
Line twoAny expression is allowed, including function calls and other templates. The conversion is the same as String(value), so an array becomes its items joined with commas, and a plain object becomes [object Object], which is rarely what you want. A newline inside the backticks is part of the string. The single exception to the conversion is a Symbol, which throws, and the full list of rules is in the post on objects to primitives.
Multiline templates keep their indentation, a detail that matters in code.
function usage() {
return `Usage:
tool <file>
tool --help`;
}
console.log(JSON.stringify(usage()));"Usage:\n tool <file>\n tool --help"The four spaces before each line are in the string because they are in the source. If you indent a template to match your code, the text carries that indentation. Dedent in a tag, in a helper, or by keeping the template flush with the left margin.
How a tag is called
A tag is a function placed directly before a template. It is called with an array of the literal pieces and then each interpolated value as a separate argument.
function show(strings, ...values) {
console.log(strings);
console.log(values);
return strings.raw.length;
}
const name = "Ada";
const count = 3;
console.log(show`Hello ${name}, you have ${count} messages`);[ 'Hello ', ', you have ', ' messages' ]
[ 'Ada', 3 ]
3The strings array always has one more entry than values, because text sits before, between and after every value. The values keep their original types. The number 3 arrived as a number, and a tag can treat it differently from the string "Ada", which a plain template cannot do because it has already turned everything into text.
The simplest tag reassembles the string, which shows the order of the pieces.
function highlight(strings, ...values) {
return strings.reduce(
(out, piece, index) =>
out + piece + (index < values.length ? `[${values[index]}]` : ""),
"",
);
}
console.log(highlight`User ${"ada"} logged in from ${"10.0.0.7"}`);User [ada] logged in from [10.0.0.7]Interleaving strings[i] and values[i] is the core pattern for every tag. Because the values are separate, a tag can escape each one, quote it, validate it or replace it with a placeholder.
A tag that parameterizes SQL
The best-known use is a query builder that prevents injection. The tag collects the fixed text, replaces each value with a numbered placeholder and returns the query with its parameters.
function sql(strings, ...values) {
const text = strings.reduce(
(query, piece, index) => query + piece + (index < values.length ? `$${index + 1}` : ""),
"",
);
return { text, values };
}
const id = 7;
const status = "active'; DROP TABLE users; --";
console.log(sql`SELECT * FROM users WHERE id = ${id} AND status = ${status}`);{
text: 'SELECT * FROM users WHERE id = $1 AND status = $2',
values: [ 7, "active'; DROP TABLE users; --" ]
}The hostile string never touches the query text. It travels as a parameter, and the database driver sends it separately from the SQL, so it can only ever be data. That is the whole defense, and it works because the tag can tell the literal text from the interpolations. Libraries such as postgres and @vercel/postgres use exactly this design, and you hand the returned object to a driver that supports parameters.
The mistake to avoid is the untagged version.
const status = "x' OR '1'='1";
const unsafe = `SELECT * FROM users WHERE status = '${status}'`;
console.log(unsafe);SELECT * FROM users WHERE status = 'x' OR '1'='1'The input closed the quote and added a condition that is always true. A template literal looks like it should be safe, and it is only a string builder. Use a tag, or a driver's parameter API, for any query that includes outside input.
Raw strings and escapes
In an ordinary template, backslash sequences are processed, so \n becomes a newline. A tag also receives the unprocessed text in strings.raw, and String.raw is a built-in tag that returns it.
console.log("a\tb".length);
console.log(String.raw`a\tb`.length);
console.log(String.raw`C:\Users\ada\notes`);
console.log(String.raw`${1}\n${2}`);
const pattern = new RegExp(String.raw`^\d{3}-\d{4}$`);
console.log(pattern.test("555-0199"));3
4
C:\Users\ada\notes
1\n2
trueString.raw is the right tool for Windows paths and regular expressions, where backslashes are the content. The interpolations still work, and only the literal text stays raw. In a normal string you would write "C:\\Users\\ada" and "^\\d{3}-\\d{4}$", doubling every backslash.
Tagged templates are allowed to contain escapes that would be a syntax error in an ordinary template. The cooked string for an invalid escape is undefined, and the raw text is preserved, so a tag can accept a mini language that uses backslashes.
const probe = (strings) => [strings[0], strings.raw[0]];
console.log(probe`\unicode and \xerxes`);[ undefined, '\\unicode and \\xerxes' ]An untagged template with \unicode is a SyntaxError, because \u must be followed by a valid code point. The tagged form is lenient, so LaTeX and similar notations can be embedded.
Caching and identity
The strings array is created once for each place in the source where a tagged template appears, frozen, and reused on every call from that spot. Libraries use this to cache parsed templates.
const calls = [];
const record = (strings) => calls.push(strings);
for (let i = 0; i < 2; i++) {
record`same ${i} site`;
}
record`same ${0} site`;
console.log(calls[0] === calls[1]);
console.log(calls[0] === calls[2]);
console.log(Object.isFrozen(calls[0]));true
false
trueThe loop called the tag twice from one source location, and both calls received the identical array. A second template with the same text at a different location got a different array. A library such as lit-html uses the identity of strings as a cache key, so it parses each template once and reuses the result for every render.
HTML escaping with a tag
Tags suit HTML, where the rule is to escape every interpolated value but not the literal markup.
const escape = (value) =>
String(value).replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
function html(strings, ...values) {
return strings.reduce(
(out, piece, index) => out + piece + (index < values.length ? escape(values[index]) : ""),
"",
);
}
const comment = '<img src=x onerror="steal()">';
console.log(html`<p class="comment">${comment}</p>`);<p class="comment"><img src=x onerror="steal()"></p>Every angle bracket and quote in the user text became a numeric entity, so the browser shows the text and never builds an element from it. The markup written by the author passes through untouched, and the user's text is neutralized. This is a sketch for learning. Production code should use a vetted library or a framework that escapes by default, since correct escaping depends on the context, whether text, attribute or URL.
Writing a tag that returns something other than a string
A tag may return any value, and several useful ones return objects. A tag that builds a URL can encode each value for a path segment and return a URL, so callers get a validated object and not a loose string.
function url(strings, ...values) {
const path = strings.reduce(
(out, piece, index) =>
out + piece + (index < values.length ? encodeURIComponent(values[index]) : ""),
"",
);
return new URL(path, "https://api.example.test");
}
const folder = "reports/2026";
const result = url`/files/${folder}/summary?v=${1}`;
console.log(result.pathname);
console.log(result.href);/files/reports%2F2026/summary
https://api.example.test/files/reports%2F2026/summary?v=1The slash inside the value was encoded as %2F, so it stays inside one path segment and cannot walk up or across the directory structure. A plain template would have produced two segments and silently changed which resource the request reaches. That is the same shape of protection as the SQL tag, applied to a different injection surface.
Where this stops being the right tool
If a tag does heavy work per call, such as parsing a template on every render, cache by the strings identity as shown. If you only want a prettier string, a plain template is enough and a tag adds a function call to read. And for large HTML or SQL, a dedicated library handles contexts and edge cases that a hand-written tag does not.
Template literals are specified under template literals, and MDN's page on template literals documents tags, raw strings and the escape rules.


