JavaScript · Modern Syntax

Template Literals

Template literals use backticks (`) instead of quotes. They make building messages and HTML snippets far easier to read.

Intermediate 5 min Lesson 25 of 49 Runnable examples
Before you start:Strings
0/49 in JavaScript
On this page · 5 min · Intermediate

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#

JavaScriptReadable messages Runnable
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());
Expected output
Hi Meera, you have 3 items.
Total: ₹148.50
Status: ready
<ul>
  <li>Meera</li>
</ul>
Opens this example in the full playground

Step-by-step explanation#

  1. ${name} and ${items} insert the variables.
  2. The calculation runs inside ${} and is formatted with toFixed.
  3. A ternary inside ${} chooses the word.
  4. 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#

Using quotes instead of backticks

'Hi ${name}' prints the text literally. Placeholders only work inside backticks.

Injecting user input into HTML

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
JavaScript Runnable
const orderId = 102, customer = 'Ravi', qty = 2, product = 'Mouse', price = 700;
console.log(`Order #${orderId} for ${customer}: ${qty} × ${product} = ₹${qty * price}`);
Opens this example in the full playground

Mini quiz#

Template Literals quizPredict the output Question 1 of 1

What is printed?

const a = 2, b = 3;
console.log(`${a} + ${b} = ${a + b}`);
Score so far: 0/0

Want more? Practise all JavaScript MCQs · JavaScript interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.