Template Literals

Course: JavaScript Beginner

Lesson 18: Template Literals

Level

Beginner

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Create template literals using backtick syntax and embed expressions with ${}
  • Write multi-line strings without escape sequences
  • Use template literals to build dynamic HTML strings and readable log messages

Frontend Development Context

Before template literals, building strings with dynamic values required concatenation with +, which is verbose and error-prone. Template literals, introduced in ES6, replaced this pattern and became one of the most-used features in modern JavaScript. In frontend development, they appear everywhere: rendering dynamic text to the DOM, constructing API URLs, building HTML card markup in JavaScript, and writing clear debugging log messages.

The ability to embed any JavaScript expression directly inside a string — not just variables, but function calls, arithmetic, ternary operators, and method chains — makes template literals powerful beyond simple variable substitution. Knowing template literals well means you can write clearer, shorter, and more maintainable string logic.

Explanation

A template literal is a string enclosed in backticks (`) instead of single or double quotes. Inside a template literal, ${expression} is an interpolation placeholder. Whatever the expression evaluates to is converted to a string and inserted at that position. The expression inside ${} can be any valid JavaScript: a variable, an arithmetic operation, a function call, a ternary, or a method chain.

Template literals support multi-line strings natively. A newline inside a template literal is a literal newline in the resulting string — no \n is needed. This is useful for building blocks of HTML markup or formatted text in JavaScript.

You can use any JavaScript expression inside ${}. This includes:

  • Variables: `Hello, ${name}`
  • Arithmetic: `Total: ${price * quantity}`
  • Ternary: `Status: ${isOnline ? "Online" : "Offline"}`
  • Method calls: `Name: ${name.toUpperCase()}`
  • Function calls: `Price: ${formatCurrency(amount)}`

Template literals can also be nested — a template literal inside another one's ${}. Keep this to a minimum to avoid unreadable code.

Tagged templates are an advanced feature where a function processes the template literal before it is returned as a string. This is used in libraries for styled components, SQL query builders, and internationalization. At the beginner level, understanding standard template literals is the goal.

Code Example

This example uses template literals to render a product card and build a formatted summary:

const product = {
  name: "Mechanical Keyboard",
  price: 129.99,
  inStock: true,
  rating: 4.7,
};

const stockLabel = product.inStock ? "In Stock" : "Out of Stock";

// Build an HTML card using a template literal
const cardHTML = `
  <div class="product-card">
    <h3>${product.name}</h3>
    <p class="price">$${product.price.toFixed(2)}</p>
    <p class="rating">Rating: ${product.rating} / 5</p>
    <span class="stock ${product.inStock ? "available" : "unavailable"}">
      ${stockLabel}
    </span>
  </div>
`;

document.querySelector("#product-container").innerHTML = cardHTML;

// Debug-friendly log with context
console.log(`[Product] Loaded: "${product.name}" | Price: $${product.price} | In Stock: ${product.inStock}`);

Code Explanation

The cardHTML template literal spans multiple lines. The whitespace and line breaks inside the template literal are preserved in the output string, which makes the resulting HTML readable and properly indented. This is one of the clearest advantages over concatenation — building a multi-line HTML string with + would require explicit \n characters and is much harder to read.

Inside the template literal, ${product.name} and ${product.price.toFixed(2)} embed the product's name and a formatted price. Note that product.price.toFixed(2) is a method call inside the ${} — the full expression is evaluated and its result (the string "129.99") is inserted.

The class on the <span> is built dynamically with a ternary expression inside ${}: ${product.inStock ? "available" : "unavailable"}. This is cleaner than building the class string separately and assigning it.

The console log line uses a template literal to build a structured, readable debug message with context prefixed by [Product]. This pattern — tagging log messages with their module or feature — makes it much easier to find relevant messages in the browser console.

Pattern Highlights

Positive Pattern: Use template literals for any string that contains more than one embedded value. Even a simple "Hello, " + name + "!" becomes more readable as `Hello, ${name}!`.

⚠️ Neutral Note: When using template literals to build innerHTML, be careful with user-provided values inside ${}. Template literals do not sanitize HTML — a string containing <script> tags will be injected and potentially executed.

Negative Pattern: Deeply nesting template literals inside ${} (a template literal inside a template literal inside another) quickly becomes unreadable. Extract complex sub-expressions into named variables first.

Common Mistakes

Mistake 1: Using single or double quotes when you need backticks

Template literals only work with backticks. Using a regular quote and then trying ${} inside it does not produce interpolation.

const name = "Alice";
const msg1 = "Hello, ${name}!"; // "${name}" is literal text, not interpolated
const msg2 = `Hello, ${name}!`; // "Hello, Alice!" — correct

console.log(msg1); // Hello, ${name}!
console.log(msg2); // Hello, Alice!

Backticks (the character to the left of 1 on most keyboards) are required for template literals.

Mistake 2: Forgetting to wrap expressions in ${} and expecting them to interpolate

Only content inside ${} is evaluated as an expression. Content outside it is literal text.

const score = 95;
const msg = `Your score: score out of 100`; // "score" is just text
const correct = `Your score: ${score} out of 100`; // "Your score: 95 out of 100"

Every variable or expression you want embedded must be inside ${}.

Mistake 3: Using string concatenation for multi-line content when a template literal would be cleaner

Building multi-line strings with + and explicit \n is verbose and hard to read.

// Messy concatenation:
const html = "<div class=\"card\">\n" +
  "  <h3>" + title + "</h3>\n" +
  "  <p>" + description + "</p>\n" +
  "</div>";

// Clean template literal:
const html2 = `
  <div class="card">
    <h3>${title}</h3>
    <p>${description}</p>
  </div>
`;

Template literals are the modern, readable solution for multi-line and multi-variable strings.

Quick Recap

  • Template literals use backticks and ${} placeholders to embed any JavaScript expression directly in a string
  • They support multi-line strings natively — line breaks inside backticks are preserved
  • Any expression is valid inside ${}: variables, arithmetic, method calls, ternaries, and function calls
  • Be careful with user-provided data inside template literals used for innerHTML — sanitize inputs to prevent XSS

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01