Frontend Development › JavaScript & TypeScript
Template Literals
Backtick strings with interpolation.
Also known as: template strings, backtick strings, string interpolation
Template literals are strings written with backticks that can embed expressions and span multiple lines.
const name = "Ana";
const items = 3;
const msg = `Hello, ${name}! You have ${items} item${items === 1 ? "" : "s"}.`;
// "Hello, Ana! You have 3 items."
const html = `
<ul>
<li>${name}</li>
</ul>
`;
Anything inside ${ ... } is a JavaScript expression: variables, math, function calls, ternaries.
Before them, you wrote "Hello, " + name + "! You have " + items + "...", which is harder to read and easy to get wrong.
Features
- Interpolation:
${expression}, converted to a string. - Multi-line: real line breaks, with no
\nneeded (the indentation is included in the string). - Nesting: you can put templates inside
${}. - Tagged templates: a function placed before the backtick receives the pieces and values. Libraries use them for SQL, CSS and GraphQL:
const query = gql`query { user(id: ${id}) { name } }`;
Cautions
- Never build SQL or HTML from user input this way. Interpolation doesn’t escape anything. It leads to SQL injection and XSS (SQL injection, HTML entities). Use parameterized queries and escaping, or tagged helpers that do it for you.
- Objects print as
[object Object]. UseJSON.stringifyor format fields explicitly. undefinedandnullappear as text, so default them (${x ?? ""}).- Leading whitespace in multi-line templates becomes part of the string.
- Escaping: use
\`for a literal backtick and\${for a literal${. - Languages differ in the syntax: Python has f-strings (string interpolation).