JavaScript Template Literals
Learn template literals, string interpolation, multiline strings, and tagged templates for cleaner code.
TL;DR
- 01Use backticks instead of quotes to declare template literals.
- 02Insert variables with
${}syntax for clean string interpolation. - 03Write multiline strings directly without escape characters or concatenation.
Tips
- 01Prefer template literals over standard string concatenation for readability when assembling strings containing multiple variables.
- 02Use a tagged template function to parse and escape user input safely when constructing HTML strings.
Warnings
- 01Remember that whitespace and indentation inside template literals are preserved, which can affect your final output layout.
- 02Avoid embedding unescaped user inputs into template literals because it introduces severe cross-site scripting vulnerabilities.
Basic Syntax
backticksCreates template literals using backticks instead of single or double quotes.
const text = `Hello, world!`;Multiline stringsWrites strings across multiple lines without using string concatenation or escape characters.
const poem = `Roses are red
Violets are blue`;Line preservationPreserves any newlines and indentation inside the template literal body automatically.
const raw = `
Indented Line
`;String Interpolation
${} syntaxInserts variables directly into strings without using the concatenation plus operator.
const name = "Alice";
const greeting = `Hello, ${name}!`;ExpressionsEvaluates any valid JavaScript expressions inside the interpolation curly braces.
const a = 5, b = 10;
const sum = `${a} + ${b} = ${a + b}`;Method callsInvokes functions or prototype methods directly inside the string interpolation.
const title = "main";
const html = `<h1>${title.toUpperCase()}</h1>`;Multiline HTML
HTML templatesBuilds complex multiline HTML string blocks with clean formatting and indentation.
const html = `
<div class="card">
<h2>${title}</h2>
</div>
`;trim() utilityTrims leading and trailing whitespace from the resulting multiline output string.
const html = `
<div>${content}</div>
`.trim();Escaping Characters
Backtick escapeEscapes the backtick character using a backslash inside a template literal.
const text = `Use \`backticks\` inside`;Special sequencesSupports standard escape sequences like tabs and newlines within backticks.
const csv = `Name\tAge\n${name}\t${age}`;Dollar sign escapeEscapes the dollar sign to prevent it from being parsed as interpolation.
const price = `Price: \$${amount}`;Tagged Templates
Tag functionIntercepts the template string components and interpolated values using a prefix function.
function tag(strings, ...values) {
return strings[0] + values[0];
}
const res = tag`Hi ${name}`;Value processingInspects and sanitizes string values before returning the final formatted output.
function clean(strings, ...values) {
return values.map(v => String(v).trim());
}Tagged CSSDefines styling or markup templates using tagged template literals.
const styles = css`
color: ${color};
font-size: 14px;
`;In Practice
Prevents cross-site scripting attacks by escaping raw user input within a custom tagged template function.
- 01Create an escaping utility function to substitute hazardous HTML brackets.
- 02Define a tagged template function that iterates over string parts and variables.
- 03Sanitize each interpolated value using the escape function before assembly.
- 04Reduce and concatenate the parts together to build the secure output string.
- 05Invoke the tagged template with potentially unsafe user object values.
function escapeHtml(str) {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
function safeHtml(strings, ...values) {
return strings.reduce((acc, str, i) => {
const rawVal = values[i - 1];
const safe = rawVal ? String(rawVal) : "";
const val = escapeHtml(safe);
return acc + val + str;
});
}
const user = {
name: "<script>alert(1)</script>",
role: "Admin"
};
const card = safeHtml`<div class="card">
<h3>${user.name}</h3>
<p>Role: ${user.role}</p>
</div>`;FAQ
Yes, template literals preserve actual line breaks. Pressing Enter inside backticks creates a real newline in the string. You do not need to use \n escape sequences anymore.
Place any valid JavaScript expression inside the ${} syntax. For example, you can write mathematical operations or function calls directly. The return value is coerced to a string automatically.
Escape the backtick using a backslash like ``` inside the template body. This prevents the backtick from incorrectly terminating the template string. The backslash is stripped out of the final output.
A tagged template passes the string segments and expression values to a custom function. This function controls how the string is constructed. Tagged templates are common in styling libraries or HTML sanitizers.
No, modern JavaScript engines optimize template literals and string concatenation equally well. There is no performance reason to choose string concatenation over template literals. Use template literals by default.