Lesson

JS String Templates

10 min reading
Free Course

JavaScript Template Literals: Backticks and Interpolation

JavaScript template literals use backticks (`...`) instead of single or double quotes to build dynamic and multiline strings. Introduced in ES6, they let you embed expressions directly inside ${...} placeholders without messy + concatenation.

String Interpolation and Expressions

You can place any valid JavaScript expression inside ${...}, including arithmetic, function calls, and ternary checks. JavaScript evaluates the expression first and converts the result into a string automatically.

Template literals also keep line breaks and indentation exactly as written in your source file. That makes formatting emails, SQL snippets, or log blocks much cleaner than joining lines with .

Practical Template Literal Example

Notice how ${...} computes discounts inline and keeps multi-line output easy to read.

const customer = "Rafi";
const subtotal = 80;
const isVip = true;

const finalTotal = isVip ? subtotal * 0.85 : subtotal;
const receipt = `Customer: ${customer}
Tier: ${isVip ? "VIP (15% off)" : "Standard"}
Amount Due: $${finalTotal.toFixed(2)}`;

console.log(receipt);

Tagged Templates in Brief

A tagged template places a function name directly before the opening backtick, such as highlight`Hello ${name}` . Libraries like styled-components and GraphQL clients use tagged templates to sanitize interpolated values or parse domain syntax safely.

Common Mistakes to Avoid

  • Using single quotes with ${}: Writing 'Hello ${name}' prints literal ${name} text because interpolation only works inside backticks.
  • Indenting inside multi-line template strings: Leading spaces inside indented functions become part of the final string unless you trim lines.
  • Building raw HTML from user input: Putting untrusted variables inside HTML template strings opens XSS vulnerabilities; escape user text or use textContent instead.

Frequently Asked Questions

Can I nest a template literal inside another template literal?

Yes, an expression inside ${...} can contain another backtick template literal, though extracting a helper variable keeps code much cleaner.

How do I write a literal backtick or dollar-brace inside a template literal?

Escape the character with a backslash, such as \` for a backtick or \${x} to print ${x} as plain text.

Are template literals slower than + concatenation?

No, modern JavaScript engines optimize template literals to match or beat string concatenation in speed.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum