*
Previous let, const, arrow functions Destructuring Next

Template Literals in JavaScript

Template Literals in JavaScript

Template literals are a modern feature in JavaScript (ES6) that allow for advanced string manipulation, such as embedding expressions and creating multiline strings. Unlike traditional strings enclosed in single (') or double (") quotes, template literals use backticks (`).

🧾 What Are Template Literals?

Template literals are string literals enclosed by `backticks` instead of single (') or double (") quotes. They support:

  • String interpolation using ${expression}
  • Multi-line strings without needing \n
  • Tagged templates for custom string processing

How to use template literals

Basic syntax

Enclose your string in backticks.

//javascript
const greeting = `Hello, world!`;
console.log(greeting); // Output: Hello, world!

String interpolation

Insert variables and JavaScript expressions directly into your string using the ${...} placeholder.

Example: Variables

//javascript
const name = "Alice";
const age = 30;

const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // Output: My name is Alice and I am 30 years old.

Example: Expressions

//javascript
const a = 10;
const b = 5;

const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // Output: The sum of 10 and 5 is 15.

Template literals also allow for embedding function calls within the ${...} placeholder.

Multiline strings

Template literals can span multiple lines without needing escape characters, preserving the line breaks within the backticks. You can see an example in the referenced document.

🧪 Syntax and Examples

// Basic interpolation
const name = "Shivshanker";
console.log(`Hello, ${name}!`);

// Multi-line string
const poem = `Roses are red,
Violets are blue,
Template literals,
Make coding new.`;

// Expression evaluation
const a = 5, b = 10;
console.log(`Sum: ${a + b}`);

// Tagged template
function emphasize(strings, ...values) {
  return strings.reduce((acc, str, i) => acc + str + (values[i]?.toUpperCase() || ""), "");
}
const mood = "excited";
console.log(emphasize`I am feeling very ${mood} today!`);

✅ Advantages

Template literals improve code readability by simplifying string interpolation and making multiline strings easy to create. They also allow the use of single and double quotes within the string without requiring escaping.

  • Readable syntax for string interpolation
  • Supports multi-line strings without escape characters
  • Dynamic expressions embedded directly in strings
  • Tagged templates allow advanced formatting or sanitization
  • Improved maintainability over string concatenation

❌ Disadvantages

While typically negligible, there might be a slight performance overhead compared to simple string literals. For very basic, static strings, standard quotes might be more immediately understandable to some developers. Additionally, using template literals for dynamic content like SQL queries or HTML requires careful handling to prevent security vulnerabilities.

  • Not supported in very old browsers (pre-ES6)
  • Overuse can reduce readability if expressions are too complex
  • Debugging tagged templates can be tricky

📌 When to Use template literals

Template literals are best used for complex string formatting involving variables or expressions, creating multiline text, and generating dynamic content like HTML or SQL queries. However, when building dynamic queries, be sure to take precautions against SQL injection attacks.

  • When combining strings with variables or expressions
  • For generating HTML or SQL templates
  • When working with multi-line strings
  • When needing custom formatting via tagged templates

🚫 When Not to Use

For simple, static strings without any variables or expressions, using standard single or double quotes can be clearer. Also, avoid using them in environments that don't support ES6 if compatibility with very old browsers is necessary.

  • For static strings with no dynamic content
  • In performance-critical code where string concatenation is faster
  • When targeting very old JavaScript environments without transpilation

Best practices, precautions, and tips

Use template literals for dynamic and multiline strings, reserving standard quotes for static ones. Remember to escape literal backticks (`) or dollar signs ($) with a backslash if needed. It is crucial to sanitize any user input embedded within template literals to prevent security risks like Cross-Site Scripting (XSS) or SQL injection. For more complex scenarios, you can nest template literals or use tagged templates for more control over string processing.

🧠 Best Practices

  • Keep expressions inside ${} simple and readable
  • Use template literals for clarity, not complexity
  • Prefer template literals over + for string concatenation
  • Use tagged templates for escaping or formatting user input

⚠️ Precautions

  • Avoid injecting untrusted data directly into template literals
  • Don’t nest too many expressions—it can hurt readability
  • Use linters or formatters to maintain clean syntax

💡 Tips

  • Use them in logging for cleaner debug messages:
    console.log(`User ${user.name} logged in at ${new Date().toISOString()}`);
  • Combine with array methods for templated lists:
    const items = ['apple', 'banana'];
    console.log(`Shopping list:\n${items.map(i => `- ${i}`).join('\n')}`);
Back to Index
Previous let, const, arrow functions Destructuring Next
*
*