Useful Cheatsheetsusefulcheatsheets.com
JavaScript Template Literals
Chapter 11 · Page 89
Beginner

JavaScript Template Literals

Learn template literals, string interpolation, multiline strings, and tagged templates for cleaner code.

TL;DR

  1. 01Use backticks instead of quotes to declare template literals.
  2. 02Insert variables with ${} syntax for clean string interpolation.
  3. 03Write multiline strings directly without escape characters or concatenation.

Tips

  1. 01Prefer template literals over standard string concatenation for readability when assembling strings containing multiple variables.
  2. 02Use a tagged template function to parse and escape user input safely when constructing HTML strings.

Warnings

  1. 01Remember that whitespace and indentation inside template literals are preserved, which can affect your final output layout.
  2. 02Avoid embedding unescaped user inputs into template literals because it introduces severe cross-site scripting vulnerabilities.
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Template Literals
Chapter 11 · Page 90
Beginner

JavaScript Template Literals

(continued)

Basic Syntax

  • backticks

    Creates template literals using backticks instead of single or double quotes.

    const text = `Hello, world!`;
  • Multiline strings

    Writes strings across multiple lines without using string concatenation or escape characters.

    const poem = `Roses are red
    Violets are blue`;
  • Line preservation

    Preserves any newlines and indentation inside the template literal body automatically.

    const raw = `
      Indented Line
    `;
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Template Literals
Chapter 11 · Page 91
Beginner

JavaScript Template Literals

(continued)

String Interpolation

  • ${} syntax

    Inserts variables directly into strings without using the concatenation plus operator.

    const name = "Alice";
    const greeting = `Hello, ${name}!`;
  • Expressions

    Evaluates any valid JavaScript expressions inside the interpolation curly braces.

    const a = 5, b = 10;
    const sum = `${a} + ${b} = ${a + b}`;
  • Method calls

    Invokes functions or prototype methods directly inside the string interpolation.

    const title = "main";
    const html = `<h1>${title.toUpperCase()}</h1>`;
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Template Literals
Chapter 11 · Page 92
Beginner

JavaScript Template Literals

(continued)

Multiline HTML

  • HTML templates

    Builds complex multiline HTML string blocks with clean formatting and indentation.

    const html = `
      <div class="card">
        <h2>${title}</h2>
      </div>
    `;
  • trim() utility

    Trims leading and trailing whitespace from the resulting multiline output string.

    const html = `
      <div>${content}</div>
    `.trim();
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Template Literals
Chapter 11 · Page 93
Beginner

JavaScript Template Literals

(continued)

Escaping Characters

  • Backtick escape

    Escapes the backtick character using a backslash inside a template literal.

    const text = `Use \`backticks\` inside`;
  • Special sequences

    Supports standard escape sequences like tabs and newlines within backticks.

    const csv = `Name\tAge\n${name}\t${age}`;
  • Dollar sign escape

    Escapes the dollar sign to prevent it from being parsed as interpolation.

    const price = `Price: \$${amount}`;
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Template Literals
Chapter 11 · Page 94
Beginner

JavaScript Template Literals

(continued)

Tagged Templates

  • Tag function

    Intercepts the template string components and interpolated values using a prefix function.

    function tag(strings, ...values) {
      return strings[0] + values[0];
    }
    const res = tag`Hi ${name}`;
  • Value processing

    Inspects and sanitizes string values before returning the final formatted output.

    function clean(strings, ...values) {
      return values.map(v => String(v).trim());
    }
  • Tagged CSS

    Defines styling or markup templates using tagged template literals.

    const styles = css`
      color: ${color};
      font-size: 14px;
    `;
Notes
Useful Cheatsheetsusefulcheatsheets.com
JavaScript Template Literals
Chapter 11 · Page 95
Beginner

JavaScript Template Literals

(FAQ)

FAQ

Yes, template literals preserve actual line breaks. Pressing Enter inside backticks creates a real newline in the string. You do not need to use \n escape sequences anymore.

Place any valid JavaScript expression inside the ${} syntax. For example, you can write mathematical operations or function calls directly. The return value is coerced to a string automatically.

Escape the backtick using a backslash like ``` inside the template body. This prevents the backtick from incorrectly terminating the template string. The backslash is stripped out of the final output.

A tagged template passes the string segments and expression values to a custom function. This function controls how the string is constructed. Tagged templates are common in styling libraries or HTML sanitizers.

No, modern JavaScript engines optimize template literals and string concatenation equally well. There is no performance reason to choose string concatenation over template literals. Use template literals by default.

Useful Cheatsheetsusefulcheatsheets.com
JavaScript Template Literals
Chapter 11 · Page 96
Beginner

JavaScript Template Literals

(In Practice)
In Practice

Sanitizing HTML with Tagged Templates

Prevents cross-site scripting attacks by escaping raw user input within a custom tagged template function.

  1. 01Create an escaping utility function to substitute hazardous HTML brackets.
  2. 02Define a tagged template function that iterates over string parts and variables.
  3. 03Sanitize each interpolated value using the escape function before assembly.
  4. 04Reduce and concatenate the parts together to build the secure output string.
  5. 05Invoke the tagged template with potentially unsafe user object values.
function escapeHtml(str) {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
}

function safeHtml(strings, ...values) {
  return strings.reduce((acc, str, i) => {
    const rawVal = values[i - 1];
    const safe = rawVal ? String(rawVal) : "";
    const val = escapeHtml(safe);
    return acc + val + str;
  });
}

const user = {
  name: "<script>alert(1)</script>",
  role: "Admin"
};

const card = safeHtml`<div class="card">
  <h3>${user.name}</h3>
  <p>Role: ${user.role}</p>
</div>`;
Takeaway

Use tagged templates to automatically sanitize user inputs, preventing cross-site scripting vulnerabilities in your HTML.