Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Tagged template literal syntax

A tag function receives a template literal’s text segments and substitution values separately. The tag’s return value becomes the value of the whole expression.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

tag`prefix ${expression} suffix`
obj.tag`prefix ${expression} suffix`

function tag(strings, ...values) { /* process the parts and return a value */ }

Tagged template literal syntax places a tag expression before a backtick-delimited template, as in tag`prefix ${expression} suffix` . JavaScript calls the tag instead of building a string first. This differs from tag(`prefix ${expression} suffix`): the untagged template converts substitutions to strings and joins them with the literal text, so the function receives one finished string.

The tag’s first argument is the array strings of literal segments. JavaScript evaluates the ${...} expressions from left to right before the call and passes their values as separate arguments without converting them to strings. A rest parameter such as ...values collects them. With n substitutions there are n + 1 segments, including any empty ones. The expression evaluates to whatever the tag returns, which need not be a string.

strings[i] is the cooked segment, with escape sequences interpreted; strings.raw[i] preserves their spelling. A malformed escape in a tagged template makes the corresponding entire cooked element undefined; without a tag it is a SyntaxError. Both arrays are frozen. Repeated evaluations of the same literal occurrence in the same ECMAScript realm reuse the same strings array. A different occurrence gets its own array, even if the text is identical.

In obj.tag`x` , the call supplies obj as the this value, just as an ordinary method call does. A non-callable tag value causes a TypeError. Direct use with optional chaining, as in obj?.tag`x` , is a SyntaxError.

This is language syntax specified in ECMAScript 2024, not a browser API. Check support in your target runtime. Tagging does not sanitize data by itself: do not pass untrusted output to innerHTML without appropriate HTML sanitization.

Examples

function inspect(strings, value) {
  return {
    cookedLength: strings[0].length,
    rawLength: strings.raw[0].length,
    valueType: typeof value,
    tail: strings[1],
  };
}

console.log(JSON.stringify(inspect`\n${7}`));

Result

{"cookedLength":1,"rawLength":2,"valueType":"number","tail":""}

`inspect` returns an object, which `JSON.stringify` turns into a string for logging. `\n` is one newline character in `strings[0]` but two characters in `strings.raw[0]`. The value `7` stays a number, and the final segment is empty.

Related lessons

  • JavaScript · Lesson 28 · Advanced · Version: 4

Sources