Glossary / Template literals

Template literals

Template literals use backticks to create strings with interpolation, multiline source text, and tagged-template processing. Interpolated expressions are evaluated and converted to strings. Tagged templates instead call a tag function with literal segments and substitution values, enabling structured domain-specific processing.

Interpolation and tags

const user = "Ada";
const message = `Welcome, ${user}!`;

function inspect(strings, ...values) {
  return { strings, values };
}
inspect`Hello ${user}, count=${3}`;

A tagged template receives a frozen array-like collection of cooked literal segments, a .raw view of source escapes, and each substitution as a separate argument. The tag may return any value—not necessarily a string. String.raw is a built-in tag that preserves raw escape sequences. Tags are useful for localization, safe query builders, and embedded DSLs when the tag understands the output context.

Crucially, an ordinary template literal does not HTML-escape, SQL-parameterize, shell-escape, or URL-encode a value. Interpolation is string conversion, not sanitization:

const html = `<p>${untrusted}</p>`; // Unsafe for untrusted HTML contexts

Use framework auto-escaping, DOM text APIs, parameterized SQL, or context-specific encoders. Multiline literal formatting preserves line breaks and indentation, which may accidentally add whitespace to generated strings.

Interview questions

  1. What arguments does a tag receive? Literal segments followed by the substitution values.
  2. Does interpolation sanitize input? No; it only converts the value to a string.
  3. Can a tag return a non-string? Yes.
  4. When use String.raw? When the raw source escape sequences are desired.

References