Template Literals
Strings written with backticks instead of quotes. They can embed expressions with ${...}, span multiple lines, and be processed by a tag function.
Detailed Explanation
Before ES6, building a string from data meant concatenation. A three-field message became a line of quotes and plus signs where a single missing space broke the output, and a multi-line string needed \n escapes or an array joined together. Template literals replaced all of that.
A template literal is delimited by backticks. Inside, ${ } marks a substitution: any expression, evaluated at the moment the literal runs, with the result converted to a string. Not a statement — an expression. Function calls, ternaries, arithmetic and nested template literals are all fine; an if block is not.
Three features come with the syntax.
Interpolation. `Hi ${user.name}, you have ${count} items` reads in the same order as the output.
Real newlines. Whatever you type between the backticks is preserved, including line breaks and leading indentation. That last part bites: a template indented inside a function carries the indentation into the string.
Tagged templates. Put a function name directly before the opening backtick and JavaScript calls it instead of building a string. The tag receives the literal string chunks as its first argument and each interpolated value as a following argument. This is a hook into the string before it is assembled, and it is how libraries implement SQL builders, styled components, and internationalisation. The strings array also carries a .raw property holding the text with escape sequences uninterpreted; String.raw is a built-in tag that uses it.
The conversion rules are worth knowing because they are the same rules as + with a string. Each value goes through ToString. An object becomes "[object Object]" unless it has a useful toString. An array becomes its elements joined by commas. null becomes "null" and undefined becomes "undefined", which is how stray undefined text reaches production UI. Guard with ?? when a value may be missing.
Cost and caveats. Performance is a non-issue: engines compile template literals to the same operations as concatenation. Readability improves for two or more substitutions and can worsen for one long expression, so pull complex logic into a variable first. Backticks inside the literal must be escaped as \`, and a literal ${ needs \${.
The security point matters most. A template literal is plain string building with no escaping. Interpolating user input into HTML and assigning it to innerHTML is an XSS hole, and interpolating into a SQL string is an injection hole. Tagged templates exist partly to fix this: a tag can escape every interpolated value before it reaches the output. Use parameterised queries and textContent rather than trusting the literal.
Code Examples
const user = { name: "Ada", credits: 3 };
// Interpolation: any expression, evaluated in place.
const greeting = `Hi ${user.name}, you have ${user.credits} credit${
user.credits === 1 ? "" : "s"
}`;
console.log(greeting); // => Hi Ada, you have 3 credits
// Newlines and indentation are preserved exactly as typed.
const block = `line one
line two`;
console.log(block.split("\n").length); // => 2
// Missing values stringify rather than disappear.
const nickname = undefined;
console.log(`Hello ${nickname}`); // => Hello undefined
console.log(`Hello ${nickname ?? "guest"}`); // => Hello guestA tagged template that HTML-escapes every interpolated value.
// A tagged template that HTML-escapes every interpolated value.
function safeHtml(strings, ...values) {
// `strings` holds the literal chunks; `values` holds the ${...} results.
return strings.reduce((out, chunk, i) => {
const value = values[i - 1]
.toString()
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
return out + value + chunk;
});
}
const comment = "<script>steal()</script>";
console.log(safeHtml`<p>${comment}</p>`);
// => <p><script>steal()</script></p>
// String.raw is a built-in tag: escapes stay literal.
console.log(String.raw`C:\new\table`); // => C:\new\tableCommon Gotchas
Interpolation is not escaping
dropping user input into an HTML or SQL template literal is an injection vulnerability. Use `textContent`, a sanitising tag function, or parameterised queries.
Indentation ends up in the string
a template written inside an indented block keeps the leading spaces on every line. Dedent manually or keep the literal flush left.
Objects stringify to `[object Object]`
interpolating a plain object gives an unhelpful placeholder. Use `JSON.stringify(value)` or pick the field you meant.
Only expressions are allowed
`${}` accepts anything that produces a value, including a nested template literal, but never a statement such as `if` or `for`.