Template Literals and Tags

Introduction: Beyond String Concatenation

In our previous lessons, we spent a lot of time learning how to manage, protect, and move data. We used destructuring to unpack objects and optional chaining to safely navigate missing information. However, eventually, you will need to display that data to a user as a readable message. In the past, JavaScript developers had to build strings by joining pieces together with the plus sign (+). This process, called concatenation, often becomes messy and hard to read, especially when you have to manage spaces or multi-line text manually.

Modern JavaScript provides a much cleaner solution called template literals. These allow you to embed variables directly into strings and handle multiple lines of text with ease. Beyond simple formatting, JavaScript also offers a powerful feature called tagged templates. This allows you to run a string through a function before it is displayed, which is incredibly useful for tasks such as formatting currency or securing user input. In this lesson, we will explore how these tools make your code more readable and your data presentation more professional within the CodeSignal IDE.

Template Literal Basics

Multi-line Strings Made Easy

One of the most frustrating parts of older JavaScript syntax was creating strings that spanned multiple lines. You used to have to add a special newline character (\n) at the end of every line or concatenate several strings together. With template literals, JavaScript respects the actual line breaks you type inside the backticks.

Looking back at our previous code example, you can see that the summary variable was defined over two separate lines within the backticks. When we printed it to the console, the output maintained that exact same structure. This makes template literals perfect for building blocks of HTML or long text messages where the visual layout is important. You no longer need to worry about manual line breaks; you simply press Enter and keep typing.

Introduction to Tagged Templates

Tagged templates take template literals to the next level. A tagged template is created by placing the name of a function — known as the tag — immediately before the opening backtick. Instead of JavaScript simply creating a string, it hands the parts of the template over to your function. This gives you total control over how the final string is built or transformed.

When you use a tag, the function receives two main sets of information. First, it receives an array of the literal string pieces. These are the parts of the text that you typed manually. Second, it receives the values of the expressions you put inside the ${} markers. By using the rest parameter (...values) that we learned about in Lesson 3, you can collect all the interpolated values into a single array, making them easy to process regardless of how many there are.

Building a Custom Formatter

Tagged Templates for Safety and Escaping

Tagged templates are also vital for security. When your application accepts input from users, there is a risk that they might enter malicious code, such as a script tag, which could break your site or steal data. This is often called a Cross-Site Scripting (XSS) attack. You can use a tagged template to "escape" this input, turning dangerous characters like < or > into safe text versions.

"use strict";

function safeHTML(strings, ...values) {
  const esc = (s) =>
    String(s).replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" }[c]));
  return strings.reduce(
    (acc, str, i) => acc + str + (i < values.length ? esc(values[i]) : ""),
    ""
  );
}

const userInput = "<script>alert(1)</script>";
console.log(safeHTML`<div>Hello, ${userInput}!</div>`);

Output:

<div>Hello, &lt;script&gt;alert(1)&lt;/script&gt;!</div>

The safeHTML function uses an internal helper called esc to find and replace dangerous characters. Just like our money formatter, it uses reduce to combine the safe, static HTML pieces with the transformed user input. This ensures that even if a user tries to inject a script, it will be rendered as harmless text rather than being executed by the browser. This pattern is often used by professional libraries to create Domain Specific Languages (DSLs) that make complex tasks safer and easier to write.

Note: This safeHTML helper is a simplified demonstration of how tagged templates work. It is only appropriate for interpolating untrusted text into standard HTML content. In production applications, security is much more complex, requiring context-aware sanitization for attributes, URLs, and CSS. For real-world projects, you should use established framework-level escaping or dedicated sanitization libraries.

Summary and Next Steps

In this lesson, we moved beyond simple string concatenation to explore the power of template literals. You learned how to use backticks and interpolation to create clean, readable strings and how to handle multi-line text without extra characters. We also introduced tagged templates, which allow you to intercept and transform your data using custom functions.

Through our examples, you saw how tagged templates can be used to format currency automatically and protect your application from security risks by escaping HTML. These tools are essential for keeping your code organized and your user interface consistent. Now, it's time to head over to the practice exercises to build your own template logic!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal