Template Literals and Tagged Templates
Backtick strings with `${}` interpolation and multi-line text, plus tagged templates — a function that intercepts a literal's pieces before they're joined.
Template Literals and Tagged Templates
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Backtick strings (`` `like this` ``) support `${expression}` interpolation anywhere inside them and preserve real line breaks, which is why they replace almost every case that used to need `+` concatenation or an escaped `\n`.
- A tagged template puts a function's name directly before the backticks (`` tag`text ${value}` ``); instead of the interpolated string, the tag function receives the literal's string pieces as an array and each interpolated value as a separate argument, before anything gets joined together.
- That array of string pieces also carries a `.raw` property — the same pieces with escape sequences left untouched, exactly as they were typed — which is unreachable from a normal, already-interpolated string.
- Tagged templates exist so a function can inspect or transform interpolated values before they become text: escaping each value for safe HTML or SQL insertion, or giving a library its own embedded syntax, like a CSS-in-JS styling API or a GraphQL query tag.
- Calling a tagged template without ever writing your own tag function is pointless busywork — the feature only earns its keep when you actually need to intercept the pieces, which is a deliberate, occasional tool, not a replacement for ordinary template literals.
The string-building problem backticks solve
Before template literals, putting a variable inside a string meant breaking
the string apart and gluing the pieces back together with +:
const greeting = "Hello, " + name + "! You have " + count + " messages.";
That works, but the moment the string gets longer or the values move
around, you’re counting quote marks and plus signs instead of reading the
sentence. Multi-line strings were worse — you either wrote one very long
line or inserted \n by hand and lost the ability to just see line
breaks in your source.
Template literals, written with backticks instead of quotes, fix both
problems at once. Any ${expression} inside the backticks gets evaluated
and dropped into the string in place:
const greeting = `Hello, ${name}! You have ${count} messages.`;
and a literal line break inside the backticks is a literal line break in the resulting string — no escape sequence required:
const message = `Dear ${name},
Your order ships tomorrow.`;
This is the version of JavaScript strings you should reach for by default
now. It’s not a stylistic preference — it reads in the order the output
actually appears, and it can express things +-concatenation makes
awkward.
Tagged templates: getting the pieces before they’re joined
A plain template literal always ends up as one finished string — by the time you have it, the interpolation already happened and you can’t undo it. A tagged template exists for the moments you need to see the pieces before that joining happens.
The syntax is a function name placed immediately before the backticks, with no parentheses and no space:
function tag(strings, ...values) {
console.log(strings); // ["Hi ", ", you are ", ""]
console.log(values); // ["Ana", 29]
}
const name = "Ana";
const age = 29;
tag`Hi ${name}, you are ${age}`;
Instead of handing tag a finished string, JavaScript hands it the
literal’s text pieces as an array (strings) and each interpolated
expression’s value as a separate argument after that. Nothing has been
concatenated — tag gets to decide what the final result looks like,
piece by piece, value by value. That array also has a .raw property
holding the exact same pieces with escape sequences left untouched, which
is useful any time you need to see backslashes exactly as typed instead of
already-interpreted — String.raw is a tag function built entirely
around that one property.
Why you’d ever want this
A tag function that just concatenates everything back together is pointless — you’d get the same result from an untagged literal with none of the ceremony. The feature earns its place when something genuinely needs to happen to each value before it becomes text.
Safe escaping. If you’re building an HTML fragment or a SQL query
string by hand, an interpolated value that happens to contain <script>
or a stray quote character can break out of the slot it was meant to fill
and become part of the surrounding structure instead of staying data. A
tag function can run every interpolated value through an escaping
function before it ever touches the final string, so a value is
guaranteed to end up as inert text no matter what it contains. This is the
same first-principles problem SQL injection and XSS exploit — a tagged
template just gives you one centralized place to close the gap, instead
of remembering to escape by hand at every call site.
Embedded mini-languages. Several well-known libraries use a tag
function to give a template literal its own syntax: a CSS-in-JS library’s
styling tag treats the literal as a block of CSS instead of plain text; a
GraphQL client’s query tag treats it as a query document. This roadmap
doesn’t teach any specific library, but recognizing the pattern — a tag
function reinterpreting a literal as something other than a plain string —
means a line like styled.div`color: red;` stops looking like magic
syntax and starts looking like exactly what it is: a function receiving
string pieces and values, same as the toy tag example above.
Where this fits
Template literals themselves depend on nothing more than the values, types, and coercion you already have — interpolation is just an expression getting evaluated and converted to a string. Tagged templates are the more advanced half of this lesson: a genuinely useful tool for the specific moment you need to intercept interpolation, not something you’ll reach for in everyday code. Knowing the mechanism now means that when you eventually meet a library that leans on it, you’ll recognize the shape immediately instead of treating it as unexplainable syntax.
Check yourself
Why does `` `Hello, ${name}!` `` replace the older `'Hello, ' + name + '!'` pattern, beyond just being shorter to type?
It embeds the expression directly where the value belongs instead of breaking the string into fragments stitched together with `+`, so the result reads in the same order it prints, and it also lets you write an actual multi-line string with real line breaks instead of manually inserting `\n` between concatenated pieces.
In `` tag`Hi ${name}, you are ${age}` ``, what exactly does the function `tag` receive — is it one already-built string?
No. `tag` receives the literal's string pieces as an array — here, `["Hi ", ", you are ", ""]` — followed by the interpolated values as separate arguments afterward: `name`, then `age`. Nothing has been joined into a single string yet; that's the whole point of tagging it.
What does the `.raw` property on a tagged template's first argument give you that the normal string pieces don't?
The same string pieces, but with escape sequences left exactly as typed instead of interpreted — so `\n` shows up as the two characters backslash-and-n, not an actual newline. Ordinary interpolated strings have already had those escapes processed and can't get that literal form back.
What's a real reason a library would use a tagged template instead of just taking a normal string as an argument?
To intercept each interpolated value before it becomes part of the final text — for example, escaping every interpolated value for safe HTML or SQL insertion so a value can never break out of its slot and inject something unintended, or treating the literal as a small embedded language (like a styling block or a query) where each piece needs its own parsing rather than being flattened into plain text up front.
What happens if you write `` `${value}` `` with no tag function in front of it — does anything intercept the pieces?
Nothing does. With no tag function, a template literal just interpolates and concatenates normally, producing an ordinary string. Tagging is opt-in: only writing a function name directly before the backticks switches the literal from building a plain string to handing your raw pieces and values to that function instead.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.