Learn template literals, string interpolation, multiline strings, and tagged templates for cleaner code.
${} syntax for clean string interpolation.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
`;${} 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>`;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();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}`;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;
`;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.
Sanitizing HTML with Tagged Templates
Prevents cross-site scripting attacks by escaping raw user input within a custom tagged template function.
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>`;Use tagged templates to automatically sanitize user inputs, preventing cross-site scripting vulnerabilities in your HTML.