JavaScript - Template Literals
Overview
Estimated time: 25–35 minutes
Template literals (backtick strings) support interpolation, multiline text, embedded expressions, and powerful tagged templates for custom processing.
Learning Objectives
- Create template literals and interpolate variables and expressions.
- Use multiline strings and escape backticks and
${...}
sequences when needed. - Apply tagged templates for sanitization/formatting and use
String.raw
for raw output.
Prerequisites
- JavaScript - Strings
- JavaScript - RegExp (recommended)
Basics: interpolation and expressions
const name = 'Ada';
const n = 3;
`Hello, ${name}! You have ${n * 2} messages.`;
// "Hello, Ada! You have 6 messages."
// Works across lines
const poem = `Roses are red\nViolets are blue`;
const poem2 = `Roses are red
Violets are blue`;
Escaping
// Escape backtick and interpolation marker
const s1 = `Use a backtick like this: \``; // contains a backtick
const s2 = `Show a template marker: \${notVar}`; // shows ${notVar}
Tagged templates
Tagged templates call a function with string fragments and interpolated values. Useful for i18n, HTML escaping, SQL building (with care), etc.
function html(strings, ...values) {
const esc = (x) => String(x)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
return strings.reduce((out, str, i) => out + str + (i < values.length ? esc(values[i]) : ''), '');
}
const user = 'Ada';
const msg = html`Hello, ${user}!
`;
// "Hello, <b>Ada</b>!
"
Raw strings
// String.raw returns backslashes as-is (no escape processing on the cooked result)
String.raw`C:\\dev\\project`;
// "C:\\dev\\project"
// With variables
const a = 5;
String.raw`Value: ${a}\nNext line?`; // interpolates a, but keeps \n literally
Common Pitfalls
- Coercion: Interpolated values are converted with
ToString
; objects become[object Object]
unless you format them. - Security: Don’t concatenate untrusted input into HTML/SQL. Use tagged templates that escape or parameterize.
- Whitespace: Multiline literals include indentation and newlines; consider
.trim()
or a helper if needed.
Try it
Run to explore interpolation, tagged templates, and raw strings: