Last modified: Jul 20, 2026

JavaScript Template Literals Guide

JavaScript template literals make string handling easier. They let you embed variables directly inside strings. No more messy concatenation with plus signs.

Template literals use backticks (`) instead of quotes. You place variables inside ${} syntax. This keeps your code clean and readable.

In this guide, you'll learn how to use template literals with variables. We'll cover syntax, examples, and common use cases. By the end, you'll write better JavaScript strings.

What Are Template Literals?

Template literals are string literals with embedded expressions. They were introduced in ES6 (ECMAScript 2015). They provide a powerful way to create strings.

Before template literals, developers used string concatenation. That approach used the + operator. It often led to messy and error-prone code.

Template literals solve this problem. They allow multi-line strings and variable interpolation. They also support expressions inside the string.

Basic Syntax

To create a template literal, use backticks instead of quotes. Here is the basic syntax:


// Template literal with backticks
let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting);

Hello, Alice!

Notice the ${name} syntax. This inserts the variable's value directly into the string. No need for + signs.

Embedding Variables

You can embed any JavaScript variable inside ${}. This includes strings, numbers, and objects. Let's see more examples:


let firstName = "John";
let lastName = "Doe";
let age = 30;

// Embedding multiple variables
let bio = `My name is ${firstName} ${lastName}. I am ${age} years old.`;
console.log(bio);

My name is John Doe. I am 30 years old.

Template literals make code more readable. You can see the string structure clearly. Variables appear right where they belong.

Using Expressions

You can also embed expressions inside template literals. This includes math operations, function calls, and ternary operators. The expression is evaluated first, then inserted.


let price = 25;
let tax = 0.08;

// Expression inside template literal
let total = `Total cost: $${price + price * tax}`;
console.log(total);

Total cost: $27

You can also call functions directly inside ${}. This keeps your strings dynamic and powerful.


function formatDate(date) {
  return date.toLocaleDateString();
}

let today = new Date();
let message = `Today's date is ${formatDate(today)}.`;
console.log(message);

Today's date is 4/1/2025.

Multi-line Strings

One big advantage of template literals is multi-line support. You can create strings that span multiple lines without escape characters. This is great for HTML or long text.


let name = "Sarah";
let address = "123 Main St";

// Multi-line string
let letter = `Dear ${name},

Thank you for your order.
Your package will ship to:

${address}

Best regards,
The Team`;

console.log(letter);

Dear Sarah,

Thank you for your order.
Your package will ship to:

123 Main St

Best regards,
The Team

Notice how the line breaks are preserved. No need for \n characters. This makes template literals perfect for formatting text.

Nested Template Literals

You can nest template literals inside each other. This is useful for complex strings. However, use this feature sparingly to keep code readable.


let user = "Bob";
let isAdmin = true;

// Nested template literal
let welcome = `Welcome, ${user}! ${isAdmin ? `You have admin access.` : `You have user access.`}`;
console.log(welcome);

Welcome, Bob! You have admin access.

In this example, the inner template literal is conditional. It shows different messages based on the isAdmin variable. This is a clean way to handle dynamic content.

Tagged Template Literals

Tagged template literals are an advanced feature. They allow you to parse template literals with a function. The function receives the string parts and variables separately.


function highlight(strings, ...values) {
  let result = "";
  strings.forEach((str, i) => {
    result += str;
    if (i < values.length) {
      result += `${values[i]}`;
    }
  });
  return result;
}

let name = "Alice";
let age = 25;
let output = highlight`Name: ${name}, Age: ${age}`;
console.log(output);

Name: Alice, Age: 25

Tagged templates are powerful for sanitization, localization, or custom formatting. They give you full control over the string output.

Common Use Cases

Template literals are used everywhere in modern JavaScript. Here are some common scenarios:

Building HTML strings: You can create HTML elements with dynamic data.


let item = "banana";
let price = 1.99;
let html = `

${item}

Price: $${price}

`; console.log(html);

banana

Price: $1.99

URL construction: Build dynamic URLs with query parameters.


let baseUrl = "https://api.example.com";
let endpoint = "users";
let userId = 42;
let url = `${baseUrl}/${endpoint}/${userId}`;
console.log(url);

https://api.example.com/users/42

Error messages: Create descriptive error messages with variable data.


let field = "email";
let value = "";
let error = `Validation error: ${field} cannot be empty.`;
console.log(error);

Validation error: email cannot be empty.

Best Practices

Follow these tips for clean template literals:

  • Use template literals for strings with variables or expressions. Avoid them for simple static strings.
  • Keep expressions inside ${} simple. If logic is complex, move it to a function.
  • Be careful with user input. Sanitize data to prevent injection attacks, especially in HTML.
  • Use multi-line template literals for readability. They help when building long strings.
  • Combine with JavaScript Variable Scope Explained to understand where variables are accessible.

Common Mistakes

Beginners often make these errors with template literals:

Mixing quotes and backticks: Always use backticks for template literals. Using single or double quotes will cause errors.


// Wrong - uses single quotes
let name = "Alice";
let wrong = 'Hello, ${name}!'; // Output: Hello, ${name}!

// Correct - uses backticks
let correct = `Hello, ${name}!`; // Output: Hello, Alice!

Forgetting the dollar sign: The $ is required before the curly braces. Without it, the variable is treated as plain text.


let age = 25;
let wrong = `I am {age} years old.`; // Output: I am {age} years old.
let correct = `I am ${age} years old.`; // Output: I am 25 years old.

Overusing template literals: For simple strings, regular quotes are fine. Use template literals only when you need interpolation or multi-line.

Performance Considerations

Template literals are generally fast. Modern JavaScript engines optimize them well. However, avoid creating template literals inside loops if possible. The overhead is minimal, but for large loops, it can add up.


// Avoid this in large loops
for (let i = 0; i < 1000; i++) {
  let msg = `Item ${i}`;
  // do something
}

// Better: Use array methods or build strings outside loops
let items = [];
for (let i = 0; i < 1000; i++) {
  items.push(`Item ${i}`);
}
let result = items.join(", ");

Template Literals vs Concatenation

Here is a quick comparison between template literals and traditional concatenation:

FeatureTemplate LiteralsString Concatenation
SyntaxBackticks with ${}Plus sign +
Multi-lineYes, naturalNeeds \n
ReadabilityHighLow for complex strings
ExpressionsDirectly supportedMust evaluate separately

Template literals are almost always the better choice. They make code cleaner and easier to maintain. For more on variable handling, see JavaScript Variable as String Guide.

Conclusion

JavaScript template literals with variables are a game-changer for string handling. They simplify code, improve readability, and reduce errors. You can embed variables, expressions, and even multi-line text with ease.

Remember to use backticks and the ${} syntax. Practice with different data types and expressions. Avoid common mistakes like mixing quotes or forgetting the dollar sign.

Template literals are now standard in modern JavaScript. They are supported in all major browsers and Node.js. Start using them today for cleaner, more maintainable code.

For more on variable topics, check out Types of JavaScript Variables to deepen your understanding.