Template literal

Also known as: template string

On this page 7

A template literal is a JavaScript string literal enclosed in backtick characters that can contain embedded expressions written as ${expression}, span multiple lines without escape sequences, and optionally be processed by a tag function. In browser JavaScript, template literals are the standard way to build dynamic text, from user messages to URLs and markup fragments, and they are also known as template strings.

Template literals were introduced in ECMAScript 2015 (ES6) and are supported by every modern browser. They replaced most uses of string concatenation with the plus operator, which was verbose and error-prone, and they enable domain-specific mini-languages through tagged templates.

How a template literal is evaluated

When the engine evaluates a template literal, it splits the source into static string segments and substitutions. Each expression inside ${ } is evaluated from left to right, converted to a string with the same rules as String(value), and joined with the surrounding segments into a new primitive string.

Any valid JavaScript expression may appear in a substitution, including function calls, ternary operators, arithmetic and even nested template literals. The result is always a string unless a tag function intercepts evaluation and returns something else.

The table below summarizes the syntax features available inside a template literal and what each produces.

FeatureSyntax inside backticksResult
Substitution${user.name}Value converted to a string
Expression${a + b} or ${ok ? 'yes' : 'no'}Evaluated result inserted
Multiline textLiteral line breaksNewlines preserved in output
Escaped backtickBackslash before a backtickLiteral backtick character
Escaped placeholder\${Literal dollar sign and brace
Template literal syntax features

Tagged templates and String.raw

A tagged template places a function name directly before the opening backtick. Instead of producing a string automatically, the engine calls the function with an array of static segments as the first argument and the evaluated substitutions as the remaining arguments. The function can return any value.

The strings array has a raw property containing the segments before escape processing. The built-in tag String.raw uses this to return text with backslashes intact, which is useful for regular expressions and Windows file paths. The strings array is also frozen and cached per call site, so libraries can use it as a stable key for memoization.

Tagged templates power several established patterns in front-end development, listed below.

Use caseWhat the tag doesBenefit
HTML templating librariesParses markup once, updates only substitutionsFast, safe DOM updates
CSS-in-JSBuilds and injects style rulesScoped component styles
GraphQL queriesParses query text into a documentValidated query objects
Escaping helpersEncodes each substitutionProtection against injection
LocalizationLooks up translated segmentsReadable translatable strings
Common tagged template uses

Template literals compared with other string forms

JavaScript offers three string delimiters: single quotes, double quotes and backticks. Single and double quotes are functionally identical, while backticks add interpolation and multiline support. The comparison below clarifies when each form behaves differently.

PropertyQuoted stringTemplate literal
InterpolationRequires concatenationNative with ${ }
Line breaksNeed escape sequencesAllowed directly
Tag functionsNot availableSupported
JSON compatibilityDouble quotes valid in JSONNot valid in JSON
Static analysisValue fully known at parse timeDepends on runtime values
String literal forms in JavaScript

Many style guides recommend plain quotes for static strings and template literals only when interpolation or multiline text is needed. This keeps intent visible and avoids accidental substitution when a string contains a literal dollar sign followed by a brace.

Practical patterns in browser code

In everyday front-end work, template literals appear wherever text depends on runtime data. Typical cases include status messages, request URLs built for the Fetch API, class name lists, log output and small markup fragments rendered by components.

When building URLs, each dynamic part should pass through encodeURIComponent before substitution, because a template literal inserts values verbatim. A search term containing an ampersand or a space would otherwise corrupt the query string. For complex query strings, the URLSearchParams interface is often clearer than a long template.

A reusable template is created by wrapping a template literal in an arrow function, such as a function that accepts an item and returns its label. Each call evaluates the substitutions again with fresh values, which is the basis of many lightweight rendering helpers that avoid a full framework.

Nested template literals are legal and useful for conditional fragments, for example inserting an optional badge only when a product is on sale. Deep nesting, however, quickly reduces readability, and extracting the inner part into a named function is usually the better design.

Security and common mistakes with template literals

The most serious misconception is that template literals escape their content. They do not. Inserting user input into a string that is then assigned to innerHTML creates a cross-site scripting (XSS) vulnerability exactly as concatenation would.

Safe practice is to use textContent for plain text, to build elements through DOM methods, or to use a tagged template from a trusted library that escapes substitutions. The same caution applies to SQL or shell commands built in Node.js, where parameterized APIs are required.

ProblemCauseFix
XSS in rendered markupRaw input assigned to innerHTMLUse textContent or an escaping tag
Unwanted indentationSource indentation kept in multiline textTrim lines or use a dedent helper
Output shows [object Object]Object converted with toStringUse JSON.stringify or pick properties
Placeholder not replacedRegular quotes used instead of backticksSwitch the delimiters to backticks
Frequent template literal problems
  • Whitespace is literal: every space and newline between the backticks becomes part of the string.
  • Substitutions are evaluated eagerly: a template literal is not a reusable template, so wrap it in a function to render it repeatedly.
  • Performance is comparable to concatenation in modern engines, so readability should drive the choice.

In everyday language

A template literal is like a fill-in-the-blanks form letter inside a program. The fixed words are written once, and marked blanks are filled automatically with current values, such as a customer’s name or the number of items in a cart.

It also lets a programmer write text over several lines exactly as it should appear. The one caution is that it does not clean up what goes into the blanks, so text typed by visitors must be handled carefully before it is shown on a web page.

Seen in the real world

A front-end developer builds a shopping cart summary for an online store. Earlier code joined more than ten pieces with plus signs to produce a message such as the item count and total price, and it regularly broke when someone forgot a space. She rewrites it as one template literal with substitutions for the count, the formatted total and the delivery date, and the line becomes readable at a glance.

For the product reviews list, she initially writes reviewer comments into innerHTML with a template literal. A security review flags the XSS risk, because a review could contain a script. She switches to a small escaping tag function that encodes every substitution before insertion. The page keeps the clear template syntax while user-supplied text is rendered safely.