Template Literals
Template Literals revolutionize string handling with embedded expressions, multiline support, and tagged templates for powerful string processing in modern JavaScript.
What are template literals in JavaScript?
Template literals are strings written with backticks (` `) instead of quotes. They let you insert expressions with ${…} and write multi-line strings without \n. For example, Hello, ${name}! You have ${count} new messages. replaces clumsy concatenation with +`.
const name = "Ada", items = 3;
const msg = `Hi ${name}, you have ${items} item${items === 1 ? "" : "s"}.`;
const html = `
<li class="item">
${name}
</li>`;Old Way (Concatenation)
"Hello " + name + "!
You have " + count + " messages."Complex, error-prone concatenation.
New Way (Template Literals)
`Hello $${name}!
You have $${count} messages.`Clean, readable string interpolation.
Interactive Template Literals Demo
Code Editor
<input id="name" value="Ada"> <input id="qty" type="number" value="3">
<div id="out"></div>Preview
Basic Interpolation
`Hello $${name}`Embed variables directly in strings.
Expression Evaluation
`Total: $${price * quantity}`Execute expressions inside templates.
Function Calls
`Date: $${formatDate()}`Call functions within templates.
Multiline Strings Made Easy
Old Way (Concatenation Hell)
const email = "Dear " + name + ",\n" +
"\n" +
"Welcome to our platform!\n" +
"Please verify your email.\n" +
"\n" +
"Best regards,\n" +
"Team";Complex escape sequences and concatenation.
New Way (Natural Multiline)
const email = `Dear ${name},
Welcome to our platform!
Please verify your email.
Best regards,
Team`;Natural line breaks and clean interpolation.
Tagged Template Literals
How Tagged Templates Work
function myTag(strings, ...values) {
// strings: array of string literals
// values: array of interpolated values
return processedString;
}
const result = myTag`Hello ${name}, you have ${count} messages`;Common Use Cases
HTML sanitization and escaping
Internationalization (i18n)
SQL query builders
Styled-components in React
Example: HTML Escaping
function html(strings, ...values) {
return strings.reduce((result, string, i) => {
const value = values[i] || '';
const escaped = String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
return result + string + escaped;
}, '');
}
const userInput = '<script>alert("xss")</script>';
const safe = html`<div>${userInput}</div>`;
// Result: <div><script>alert("xss")</script></div>Real-World Applications
Dynamic SQL Queries
const query = `
SELECT ${columns.join(', ')}
FROM ${tableName}
WHERE ${conditions.map(c =>
`${c.field} = '${c.value}'`
).join(' AND ')}
ORDER BY ${sortField} ${sortOrder}
LIMIT ${limit}`;Build complex queries dynamically with clean syntax.
Email Templates
const welcomeEmail = `
Dear ${user.firstName},
Welcome to ${companyName}!
Your account details:
- Email: ${user.email}
- Plan: ${user.plan}
- Expires: ${formatDate(user.expiryDate)}
${user.isTrialUser ?
'Your trial expires in 7 days.' :
'Thank you for being a premium member!'
}
Best regards,
The ${companyName} Team`;Create personalized email content easily.
Configuration Files
const dockerFile = `
FROM ${baseImage}
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE ${port}
ENV NODE_ENV=${environment}
CMD ["npm", "start"]`;Generate configuration files from variables.
URL Building
const apiUrl = `
${protocol}://${hostname}:${port}/${version}/${endpoint}?
${Object.entries(params)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join('&')}`;
// Example result:
// https://api.example.com:3000/v1/users?
// page=1&limit=10&filter=activeBuild complex URLs with proper encoding.
Best Practices
Use for string interpolation
Perfect for multiline strings
Great for HTML/SQL generation
Tagged templates for processing
Security Considerations
Sanitize user input in templates
Validate data before interpolation
Escape HTML when generating markup
Use tagged templates for safe HTML
Template literals — step by step
Basic interpolation and multi-line strings
Template literals use backticks (`) instead of quotes. Embed any expression with ${...}: const msg = `Hello, ${user.name}!`. Multi-line strings just work — no more \n or string concatenation. The expression inside ${} can be any valid JavaScript: function calls, ternaries, math, method chains.
🎯 Quick Check
What is a tagged template literal?
JavaScript Template Literals: summary
Key points
- Any expression works inside
${}: maths, function calls and ternaries. - Tagged templates (`
tagtext ${x}`) pass the parts to a function, which is how libraries like styled-components work. - Building HTML with templates and
innerHTMLis unsafe with user input; escape it or usetextContent.
Frequently asked questions
›How do I write a backtick inside a template literal?
Escape it with a backslash: ` \ ``.