JS Template Literals
Template literals are backtick strings with embedded expressions. They replace string concatenation, support multi-line literals, and unlock tagged templates for safer DSLs.
The basics
JS
const name = "Ada", age = 36;
// Interpolation
`Hi, ${name}, age ${age}.` // "Hi, Ada, age 36."
// Expressions
`Total: $${(qty * price).toFixed(2)}`
// Multi-line
`
<article>
<h1>${name}</h1>
</article>
`
Tagged templates
A tag is a function that receives the static parts and the interpolated values separately — useful for sanitisation and DSLs.
JS
function safe(strings, ...values) {
return strings.reduce((acc, s, i) => {
const v = values[i - 1];
return acc + (v === undefined ? "" : escapeHtml(v)) + s;
});
}
const html = safe`<p>Hi ${userName}</p>`;
Practical uses
| Use | Example tag |
|---|---|
| HTML escaping | Lit's html tag |
| CSS-in-JS | styled-components' css tag |
| SQL templating | sql.js, slonik |
| i18n | The t tag in many libraries |
Tip: When the engine sees the same template at the same site repeatedly, the array of strings is cached — that's why tagged templates are cheap to call in a loop.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Template Literals!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Interpolate `name` into a template literal.
const msg = `Hi,
{name}!`;
Single character that starts interpolation.
Discussion
Loading…