Template Literals
Template literals use backticks (`) instead of quotes. They make building messages and HTML snippets far easier to read.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 27, 2026
Related tutorials
Learning objectives#
- Insert values with ${}
- Write multi-line strings
- Embed expressions and ternaries
- Know when to escape output
Explanation#
Backtick strings can contain placeholders: `Hi ${name}` inserts the value of name.
Any expression works inside ${}: maths, function calls, ternaries.
Line breaks inside backticks are kept, so multi-line text is easy.
When inserting user input into HTML, never use innerHTML with raw values — escape it or use textContent.
Code example: Readable messages#
const name = 'Meera', items = 3, price = 49.5;
console.log(`Hi ${name}, you have ${items} items.`);
console.log(`Total: ₹${(items * price).toFixed(2)}`);
console.log(`Status: ${items > 0 ? 'ready' : 'empty'}`);
const html = `
<ul>
<li>${name}</li>
</ul>`;
console.log(html.trim());
Hi Meera, you have 3 items. Total: ₹148.50 Status: ready <ul> <li>Meera</li> </ul>
Step-by-step explanation#
- ${name} and ${items} insert the variables.
- The calculation runs inside ${} and is formatted with toFixed.
- A ternary inside ${} chooses the word.
- The multi-line template keeps its line breaks; trim removes the leading newline.
Real-world use case#
Building notification messages, URLs (`/api/users/${id}`) and small HTML snippets.
Common mistakes#
'Hi ${name}' prints the text literally. Placeholders only work inside backticks.
element.innerHTML = `<p>${comment}</p>` allows script injection (XSS). Use textContent or escape the value.
Best practices#
- Prefer template literals over + concatenation
- Keep expressions inside ${} short
- Never put untrusted input into innerHTML
- Use encodeURIComponent for values in URLs
Remember this#
Backticks ` unlock ${superpowers}.
Anything inside ${} is JavaScript.
User input + innerHTML = danger.
Practice exercise#
Your task: Build the message "Order #102 for Ravi: 2 × Mouse = ₹1400" from variables orderId, customer, qty, product and price (700).
Show solution
const orderId = 102, customer = 'Ravi', qty = 2, product = 'Mouse', price = 700;
console.log(`Order #${orderId} for ${customer}: ${qty} × ${product} = ₹${qty * price}`);
Mini quiz#
What is printed?
const a = 2, b = 3;
console.log(`${a} + ${b} = ${a + b}`);
Want more? Practise all JavaScript MCQs · JavaScript interview questions
My notes#
Saved in this browser.