Skip to article content
FrontendXLesson 16 / 30

Template Literals and Tagged Templates

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

beginner · about 30 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Interpolate values and build multi-line strings with template literals.
  • Explain what a tag function receives and return a custom result.
  • Use a tag to escape interpolated values safely.

Overview

#

Interpolation and multi-line strings

A template literal is written with backticks. It can span multiple lines and embed expressions with the dollar-brace syntax. The embedded value is converted to a string unless the literal is passed to a tag function.

snippet.js
const name = 'Ada';
console.log(`Hello, ${name}!
Welcome.`);

Tagged templates

A tag is a function placed before a template literal. It receives the static string parts as an array and the interpolated values as the remaining arguments. This lets a tag decide how to combine them, which is how libraries build styled components and safe HTML helpers.

snippet.js
function upper(strings, ...values) {
  return strings.reduce((out, part, i) => out + part + (values[i] ? String(values[i]).toUpperCase() : ''), '');
}
console.log(upper`hi ${'there'}`); // hi THERE

Escaping and safety

Interpolating raw user input into HTML creates an injection risk. A tag function can escape each value before joining, so the static parts stay trusted and the dynamic parts are neutralized. String.raw is a built-in tag that keeps backslashes literal, which is useful for paths and patterns.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What does this tagged template call print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    function tag(strings, ...values) {
      return strings.raw.join('|') + '#' + values.join(',');
    }
    console.log(tag\`a\${1}b\${2}c\`);
    Choose the best answer
  2. Exercise 2Explain

    Explain the arguments a tag function receives and why the static parts are passed separately.

    starter.text
    function tag(strings, ...values) { return strings.length + ':' + values.length; }

    Reveal the reference answer
    reference.text
    The first argument is an array of the literal text between the interpolations, with a raw property holding the unescaped source. The remaining arguments are the evaluated values in order. Keeping them separate lets the tag escape or transform each value while trusting the static parts, which is what makes safe HTML and styled-component tags possible.

    Authored expected output: a count of strings and values

    Separating static text from dynamic values is the whole point of a tag. It gives the tag authority over how untrusted values are inserted.

  3. Exercise 3Implement

    Implement `html` as a tag that escapes every interpolated value. Running `console.log(html\`<p>\${'<b>hi</b>'}</p>\`)` should print `<p>&lt;b&gt;hi&lt;/b&gt;</p>`.

    starter.javascript
    function escapeHtml(value) {
      return String(value).replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));
    }
    function html(strings, ...values) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function escapeHtml(value) {
      return String(value).replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));
    }
    function html(strings, ...values) {
      return strings.reduce((out, part, i) => out + part + (i < values.length ? escapeHtml(values[i]) : ''), '');
    }

    Authored expected output: <p>&lt;b&gt;hi&lt;/b&gt;</p>

    The tag keeps the static tags from the template and escapes only the interpolated values, so user input cannot inject markup.

  4. Exercise 4Debug

    This helper is meant to show a user name safely but allows markup through. Find and fix the bug.

    starter.javascript
    function greet(name) {
      return `<span>Hello ${name}</span>`;
    }
    console.log(greet('<img src=x onerror=alert(1)>'));

    Reveal the reference answer
    reference.javascript
    function escapeHtml(value) {
      return String(value).replace(/[&<>"']/g, (ch) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]));
    }
    function greet(name) {
      return `<span>Hello ${escapeHtml(name)}</span>`;
    }
    console.log(greet('<img src=x onerror=alert(1)>'));

    Authored expected output: <span>Hello &lt;img src=x onerror=alert(1)&gt;</span>

    A template literal inserts the raw string. Escaping the interpolated value turns the angle brackets into text so the browser cannot treat them as markup.

  5. Exercise 5Test

    Write assertions that prove interpolation converts values and that String.raw keeps backslashes literal.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    assertEqual(`${1 + 1}`, '2', 'expression is converted to string');
    assertEqual(String.raw`a\nb`, 'a\\nb', 'String.raw keeps the backslash');
    assertEqual(`line1
    line2`.split('\n').length, 2, 'template literals span lines');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    Interpolation stringifies the result of the expression. String.raw reads the raw text, so a backslash-n stays two characters instead of becoming a newline.

  6. Exercise 6Interview

    When would you avoid a template literal?

    Reveal the reference answer
    reference.text
    I avoid interpolating untrusted input into HTML without escaping, because a template literal does no escaping on its own. I avoid building SQL or shell commands from templates, since that is an injection risk, and I prefer parameterized APIs. For hot loops I may use plain concatenation or an array join when profiling shows the template is a bottleneck, but I only optimize after measuring.

    The answer should name injection risk in HTML, SQL and shell contexts, and should treat performance as a measured concern rather than an assumption.

Common misconceptions

#
  • Template literals are always faster than string concatenation.
  • A tag function receives the already-joined string.
  • Interpolating user input into HTML is safe because it is just a string.

Follow-up practice

#
  • javascript-foundations-regular-expressions
  • javascript-foundations-dom-and-events

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.