JAVASCRIPT

JavaScript Template Literals: Syntax, Usage, and Examples

JavaScript template literals provide a modern and flexible way to handle strings. They allow for string interpolation, multi-line strings, and embedded expressions, making them a powerful alternative to traditional concatenation.

How to Use Template Literals in JavaScript

Template literals are enclosed in backticks (````) instead of quotes (" or '). They support string interpolation, allowing variables and expressions to be inserted using ${}.

let name = "Alice";
let message = `Hello, ${name}!`;
console.log(message); // Output: Hello, Alice!

In this example, the variable name is inserted into the string without using concatenation, making the code easier to read and maintain.

Multi-line Strings with Template Literals

Unlike traditional strings, template literals let you write multi-line strings without needing escape characters (\n).

let multiline = `This is line one
This is line two
This is line three`;
console.log(multiline);

By using backticks, you can preserve line breaks directly in the string, improving readability.

When to Use Template Literals in JavaScript

Template literals improve readability and maintainability, especially when dealing with dynamic content. Some common use cases include:

  1. String interpolation to embed variables and expressions inside strings.
  2. Multi-line strings to format text across multiple lines without escape characters.
  3. Dynamic content generation for constructing messages, HTML templates, or SQL queries.
  4. Conditional statements to simplify logic inside strings.
  5. Tagged templates to process template literals using functions.

Examples of Template Literals in JavaScript

String Interpolation

Instead of manually concatenating strings, template literals allow you to insert variables directly into a string.

let product = "T-shirt";
let price = 20;
console.log(`The ${product} costs $${price}.`); // Output: The T-shirt costs $20.

This approach makes the code shorter and easier to understand compared to using the + operator.

Conditional Statements in Template Literals

You can use ternary operators within template literals for simple conditional logic.

let loggedIn = true;
let greeting = `Welcome, ${loggedIn ? "User" : "Guest"}!`;
console.log(greeting); // Output: Welcome, User!

This eliminates the need for extra if statements when constructing strings dynamically.

JavaScript Template Literals vs. String Concatenation

Template literals replace traditional concatenation (+ operator) for cleaner code.

// Using string concatenation
let oldWay = "Hello, " + name + "! Your order total is $" + price + ".";

// Using template literals
let newWay = `Hello, ${name}! Your order total is $${price}.`;

console.log(oldWay === newWay); // Output: true

By using template literals, you avoid the repetitive + operator, making the code more readable.

Multi-line HTML Templates

Creating dynamic HTML structures is simpler with template literals.

let title = "Welcome";
let content = "This is your homepage.";

let htmlTemplate = `
  <h1>${title}</h1>
  <p>${content}</p>
`;

console.log(htmlTemplate);

This approach allows you to write structured HTML without needing concatenation or escape characters.

Learn More About JavaScript Template Literals

Using JavaScript Template Literals in Conditionals

You can combine conditions and expressions inside template literals.

let discount = 10;
let total = 50;

let finalMessage = `Your total is $${total - (discount ? discount : 0)}.`;
console.log(finalMessage); // Output: Your total is $40.

This keeps logic inside the template and avoids separate variable assignments.

JavaScript Tagged Template Literals

Tagged template literals process template strings using a function before outputting them.

function highlight(strings, ...values) {
  return strings.map((str, i) => `${str} <strong>${values[i] || ""}</strong>`).join("");
}

let name = "Alice";
let age = 25;

console.log(highlight`Name: ${name}, Age: ${age}`);
// Output: Name: <strong>Alice</strong>, Age: <strong>25</strong>

Here, the function modifies the output before displaying it, which can be useful for styling or formatting.

Using JavaScript Template Literals with an If Statement

You can simplify string-based conditions inside template literals.

let isMember = false;
let message = `Welcome ${isMember ? "back" : "to our site"}!`;
console.log(message); // Output: Welcome to our site!

This keeps the conditional logic inside the string declaration, making it easier to follow.

Writing JavaScript Template Literals in Functions

Functions can return formatted strings using template literals.

function greeting(name) {
  return `Hello, ${name}!`;
}

console.log(greeting("John")); // Output: Hello, John!

This makes functions that return messages or logs much simpler.

String Template Literals and Expressions

You can perform calculations inside template literals.

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

This allows mathematical expressions to be directly embedded inside strings.

JavaScript Template Literals for JSON Formatting

Template literals can format JSON output dynamically.

let user = { name: "Alice", age: 25 };
let jsonData = `{
  "name": "${user.name}",
  "age": ${user.age}
}`;

console.log(jsonData);

This is useful when dynamically generating JSON from objects.

Using JavaScript Template Literals with Arrays

You can loop through arrays inside template literals.

let fruits = ["Apples", "Bananas", "Cherries"];
console.log(`My favorite fruits: ${fruits.join(", ")}.`);

Instead of manually concatenating array elements, join() is used to create a readable list.

Using Template Literals for Dynamic CSS Styles

You can generate CSS styles dynamically using template literals.

let primaryColor = "blue";
let css = `
  body {
    background-color: ${primaryColor};
  }
`;

console.log(css);

This is useful for applying styles dynamically in JavaScript applications.

JavaScript Template Literals for SQL Queries

Template literals can construct SQL queries dynamically.

let table = "users";
let sql = `SELECT * FROM ${table} WHERE age > 18;`;

console.log(sql); // Output: SELECT * FROM users WHERE age > 18;

This approach makes it easier to build queries dynamically based on input values.

JavaScript template literals provide a more flexible and readable way to handle strings compared to traditional concatenation. They allow variables, expressions, and multi-line text to be embedded directly into strings using backticks.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH