JavaScript Reference ยท Operators
Template literals
Reference for JavaScript template literals: backtick strings, ${} interpolation, multi-line text, tagged templates, raw strings and escaping rules.
A template literal is a string written between backticks. It can contain ${expression} placeholders, which are evaluated and converted to strings, and it may span several lines without any escape sequences. Put a function name in front of the opening backtick and you get a tagged template, where the function receives the literal pieces and the interpolated values separately and decides what to return.
`Hello, ${name}!`
tag`Hello, ${name}!`
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
`text`
`text ${expression} more text`
tagFunction`text ${expression} more text`
| Part | Description |
|---|---|
`...` |
The template. Backslash escapes work as in normal strings, plus \` and \$. |
${expression} |
Any expression. Its value is converted to a string, as if by the string conversion used by String(value), except that symbols throw. |
tagFunction |
Any expression that evaluates to a function (including member expressions like String.raw). |
Tag function arguments: the first argument is an array of the string pieces (always one more than there are values) with a raw property holding the unprocessed text. The remaining arguments are the interpolated values, unconverted. The function may return any value, not just a string.
Return value: an untagged template evaluates to a string. A tagged template evaluates to whatever the tag returns.
Exceptions: interpolating a Symbol throws a TypeError. An invalid escape sequence such as \u{ or \xZ is a syntax error in an untagged template; in a tagged template it is allowed, and the cooked string for that piece is undefined while raw keeps the text.
Usage notes
- Whitespace is literal. Indentation and line breaks inside the backticks end up in the string. Line endings are normalized to
\n. - Conversion rules. Objects become
[object Object]unless they definetoString(), arrays join with commas, andnullandundefinedbecome the wordsnullandundefined. - The strings array is frozen and the same array object is passed on every evaluation of the same tagged-template site, so tags can cache work by using it as a key.
- Never build HTML or SQL by plain interpolation of user input. Use a tag that escapes values, or parameterized queries.
- Not for localization. Interpolated text cannot be reordered by translators; use a proper i18n approach.
- Nesting is fine: a template literal can appear inside
${ }of another. String.rawis the built-in tag that returns the raw text, handy for regex sources and Windows paths.
Browser support
Template literals and tagged templates work in every current browser (ES2015). Relaxed escape rules in tagged templates (ES2018) are also available in current browsers.