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.

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
    `;

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>`;

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();

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}`;

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;
    `;

In Practice

FAQ