In our first two lessons, we explored how to use the Proxy object and the Reflect API to watch and control how objects behave. We learned how to intercept property lookups and changes to build a reactive system. This is a powerful form of meta-programming because we are writing code that manages other code. However, meta-programming is not just about objects. Sometimes, we want to intercept the way JavaScript handles text and strings to create specialized tools.
This lesson introduces you to a new way to extend JavaScript by building Domain-Specific Languages, or DSLs. A DSL is a mini-language designed for a specific task, such as writing database queries or styling a website. While JavaScript is a general-purpose language, it allows us to "tag" template literals — those strings that use backticks — to change how they are processed. This gives us the power to transform data before it ever becomes a final string, which is incredibly useful for security and formatting.
We will focus on a few practical examples of DSLs. First, we will build a sql formatting tag — and learn why manual escaping is not real security, which leads us to the safer parameterized-query pattern that professional database drivers use. After that, we will create a tool that cleans up multi-line styling code to make it more compact. These patterns are used by many modern libraries you might encounter in the industry, and understanding them will help you write more secure and readable code.
How Tagged Template Literals Work
Usually, when we use template literals, JavaScript automatically joins the strings and the variables together. However, if we put the name of a function right before the opening backtick, that function becomes a tag. This tag function intercepts the string before it is finished. Instead of getting one big string, the function receives two separate inputs: an array of the literal string pieces and a list of the values we want to insert into those pieces.
The tag function receives the string parts as the first argument. The variables or expressions we put inside ${} are passed as the following arguments. By using the rest operator ..., we can collect all those interpolated values into a single array. This separation is the "secret sauce" of tagged templates. Because the values are still separate from the text, we can inspect, change, or even reject them before they are combined into the final result.
On the CodeSignal IDE, you have access to modern JavaScript features that support this syntax natively. You do not need to install any external libraries to start building these tags. By understanding this structure, you gain total control over how strings are built in your application.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Building a SQL String-Formatting Tag
Tags Can Return Any Value: Parameterized Queries
Building a CSS-in-JS Formatting Tag
Another common use for tagged templates is creating a CSS-in-JS system. Many developers like to write their website styles directly inside their JavaScript files. However, writing these styles over multiple lines with extra spaces can make the final output look messy or unnecessarily large. We can create a css tag that joins these styles together and removes the extra whitespace.
The css tag works similarly to the sql tag, but instead of focusing on security, it focuses on formatting. It joins the strings and values into one raw string first. Then, it uses a regular expression to find any groups of whitespace — like tabs or new lines — and replaces them with a single space. Finally, it trims any extra space from the very beginning and the very end of the string.
function css(strings, ...values) { // Combine everything into one string const raw = strings.reduce( (acc, s, i) => acc + s + (i < values.length ? values[i] : ""), "" ); // Remove extra spaces, new lines, and tabs return raw.trim().replace(/\s+/g, " ");}const color = "tomato";const style = css` color: ${color}; font-weight: bold;`;console.log(style);
When you look at the output of this function, you will see that the multi-line string has been converted into a single, clean line of text.
color: tomato; font-weight: bold;
This makes the data much easier to work with if you are sending it to a browser or saving it to a file. It demonstrates that tagged templates can be used for "cleaning" text just as easily as they can be used for data transformation.
Note: Collapsing all whitespace with a single regular expression is fine for a learning demo, but it is not a safe general-purpose CSS minifier. Whitespace can be meaningful inside strings, the content property, url(...) values, and custom properties, so collapsing it blindly can corrupt real stylesheets. Production tooling uses real CSS parsers/minifiers rather than a single regex.
Summary and Practice Preparation
In this lesson, we transitioned from managing objects with Proxies to managing syntax with Tagged Template Literals. You learned how a tag function intercepts a template literal and separates the text from the variables. We explored how to use the map and reduce functions to process those values and reassemble the string into a finished product.
We built a sql formatting tag to practice the value-processing pattern — including handling numbers explicitly and rejecting unsupported types — then saw the genuinely safe parameterized query approach, where a tag returns a { text, params } object so values stay separate from the SQL text. We also built a css tag to clean up styling code. Both of these examples follow the same core pattern: receive the pieces, transform the content, and reassemble the results. This technique allows you to extend the JavaScript language itself to fit the specific needs of your project.
In the upcoming practice exercises, you will have the chance to write your own tag functions. You will practice handling different data types, escaping characters, and manipulating string formatting. These skills are essential for building advanced libraries and secure integrations in modern web applications.
A popular way to introduce tagged templates is to build a sql tag that combines a query string with some values. A naive version of this tag also tries to make string values "safer" by escaping them — for example, by doubling any single quote ' into '', which is how many databases represent a literal quote inside a string.
In the example below, the sql function looks at all the values being passed into the template. It uses the map method to check each value. If a value is a string, it doubles any internal single quotes and wraps the value in quotes. If a value is a finite number, it is safe to insert directly, so we convert it with String. Any other type — a boolean, null, undefined, an object, or a non-finite number like NaN or Infinity — is rejected with an error rather than being blindly stringified into something the database would misinterpret. Once the values are processed, we use reduce to stitch the original strings pieces and the processed values back together into one final string.
JavaScript
"use strict";function sql(strings, ...values) { // Step 1: Format each value based on its type const safe = values.map((v) => { if (typeof v === "string") return `'${v.replace(/'/g, "''")}'`; if (typeof v === "number" && Number.isFinite(v)) return String(v); throw new TypeError(`Unsupported SQL value: ${String(v)} (${typeof v})`); }); // Step 2: Combine the strings and the formatted values return strings.reduce( (acc, str, i) => acc + str + (i < safe.length ? safe[i] : ""), "" );}const owner = "O'Brien";const minAge = 30;const query = sql`SELECT * FROM accounts WHERE owner = ${owner} AND age > ${minAge}`;console.log(query);
When you run this code, the output shows that the name "O'Brien" has had its single quote doubled.
text
SELECT * FROM accounts WHERE owner = 'O''Brien' AND age > 30
⚠️ Important — this is a formatting demo, not real SQL security. Manually doubling quotes is not a sufficient defense against SQL injection. It handles only one character in one context and is easy to get wrong once you add dates, identifiers, encodings, or database-specific quoting rules. Notice also how much care the type handling already requires: numbers must be checked for finiteness, and every other type has to be rejected explicitly, because there is no single correct way to turn a boolean, null, or an object into safe SQL text. Treat the sql tag above purely as a string-formatting exercise to practice the map/reduce pattern. The next section shows the approach real database drivers use: parameterized queries, where the values are never concatenated into the SQL text at all.
The logic inside reduce ensures that we pick the correct string piece, add the corresponding processed value, and handle the fact that there is usually one more string piece than there are values. This "combine the pieces" structure is the foundation of almost every tagged template — what changes is how you process the values.
So far, every tag we have written returned a string. But a tag function is just a function — it can return any value at all, including an object, an array, or a class instance. This unlocks tools that are far more powerful than simple string building.
The professional way to protect against SQL injection is to never place user values into the query text. Instead you build a parameterized query (also called a prepared statement): the SQL text contains placeholders, and the real values travel separately in a params array. The database engine combines them safely, treating the values strictly as data and never as executable SQL.
The exact placeholder syntax is database-specific. The example below uses numbered placeholders like $1 and $2, which is what PostgreSQL expects. Other databases differ: MySQL and SQLite use a positional question mark ?, SQL Server uses named parameters like @p1, and Oracle uses :name. Real drivers know their own dialect, so in practice you would pick the placeholder style that matches your database (or let a query builder handle it for you). We model the PostgreSQL style here by having our sql tag return an object with two properties: text and params.
JavaScript
function sql(strings, ...values) { // Replace each interpolation with a positional placeholder ($1, $2, ...) // NOTE: $1/$2 is PostgreSQL's syntax; other databases use ?, @p1, :name, etc. const text = strings.reduce((acc, str, i) => { const placeholder = i < values.length ? `$${i + 1}` : ""; return acc + str + placeholder; }, ""); // Keep the raw values separate — the driver binds them safely return { text, params: values };}const owner = "O'Brien";const minAge = 30;const query = sql`SELECT * FROM accounts WHERE owner = ${owner} AND age > ${minAge}`;console.log(query);
The output is not a finished SQL string but a structured object:
JavaScript
{ text: 'SELECT * FROM accounts WHERE owner = $1 AND age > $2', params: [ "O'Brien", 30 ]}
The value O'Brien is passed through completely untouched — there is no escaping to get wrong, because the value is never part of the SQL text. This is why parameterized queries also sidestep the messy type-handling problem from the previous section: numbers, strings, booleans, null, and dates are all handed to the driver as raw data, and the driver binds each one correctly for its dialect. This is the pattern you should reach for in real applications, and it is exactly what you will build in this lesson's final practice.
JavaScript
function css(strings, ...values) { // Combine everything into one string const raw = strings.reduce( (acc, s, i) => acc + s + (i < values.length ? values[i] : ""), "" ); // Remove extra spaces, new lines, and tabs return raw.trim().replace(/\s+/g, " ");}const color = "tomato";const style = css` color: ${color}; font-weight: bold;`;console.log(style);