JavaScript Template Literals

JavaScript template literals are a modern way to create and format strings. Introduced in ES6 (ECMAScript 2015), template literals make it easier to insert variables into strings, evaluate expressions inside text, and create multiline strings without complicated concatenation.

Before template literals, developers commonly used quotation marks and the + operator to combine strings with variables. Template literals provide a cleaner and more readable alternative.

In this tutorial, you will learn about template strings, string interpolation, and multiline strings with practical JavaScript examples.

What Are Template Literals in JavaScript?

Template literals are string literals enclosed in backticks (`) instead of single (') or double (") quotation marks.

They allow you to insert variables and expressions directly into a string using the ${} syntax. They also support multiline strings while preserving line breaks.

Example of a Template Literal

const name = "Alex";

const message = `Hello, ${name}!`;

console.log(message);

Output:

Hello, Alex!

In this example, the backticks define the template literal, and ${name} inserts the value of the name variable into the string.

Template literals are especially useful when displaying dynamic content on websites or combining multiple values in a message.

Template Strings in JavaScript

A template string is another name commonly used for a string created with a template literal. Template strings allow you to combine text and dynamic values in a single expression.

Before ES6, developers typically used string concatenation.

Using Traditional String Concatenation

const name = "Sarah";
const age = 25;

const message = "My name is " + name + " and I am " + age + " years old.";

console.log(message);

Output:

My name is Sarah and I am 25 years old.

Although this works, adding several variables can make the code difficult to read.

Using Template Strings

const name = "Sarah";
const age = 25;

const message = `My name is ${name} and I am ${age} years old.`;

console.log(message);

Output:

My name is Sarah and I am 25 years old.

The template literal produces the same output with cleaner syntax.

When Should You Use Template Strings?

Template strings are useful when you need to:

  • Display variables inside messages.
  • Combine text with calculated values.
  • Generate dynamic HTML content.
  • Format user information.
  • Create readable messages containing multiple values.

You can learn more about basic string operations in the JavaScript Strings tutorial:

String Interpolation in JavaScript

String interpolation means inserting the value of a variable or the result of an expression directly into a string.

JavaScript template literals support interpolation through the ${} syntax.

The general syntax is:

`Text ${expression} more text`

The expression inside ${} is evaluated, and its result becomes part of the string.

Example: Interpolating Variables

const firstName = "John";
const lastName = "Smith";

const fullName = `${firstName} ${lastName}`;

console.log(fullName);

Output:

John Smith

JavaScript inserts the values of both variables into the template literal.

Example: Interpolating Expressions

You can also include calculations and other expressions inside ${}.

const price = 500;
const quantity = 3;

const total = `Total price: ₹${price * quantity}`;

console.log(total);

Output:

Total price: ₹1500

JavaScript calculates price * quantity and inserts the result into the string.

Example: Using a Function Inside a Template Literal

You can call a function inside the interpolation expression.

function multiply(a, b) {
    return a * b;
}

const message = `The result is ${multiply(4, 5)}.`;

console.log(message);

Output:

The result is 20.

The function executes, and its return value is inserted into the string.

Example: Conditional Expressions

You can use a conditional expression inside a template literal to display different messages.

const age = 20;

const message = `You are ${age >= 18 ? "an adult" : "a minor"}.`;

console.log(message);

Output:

You are an adult.

This approach is useful for generating dynamic messages based on conditions.

For more information about functions and conditions, explore these JavaScript tutorials:

https://web4learners.com/javascript/javascript-conditional-statements

Multiline Strings in JavaScript

Multiline strings contain text across multiple lines.

Before ES6, developers often used the \n escape sequence or combined multiple strings to create line breaks. Template literals allow you to write multiline strings directly while preserving the line breaks.

Creating a Multiline String

const message = `Welcome to JavaScript.
Learn template literals.
Practice with examples.`;

console.log(message);

Output:

Welcome to JavaScript.
Learn template literals.
Practice with examples.

Each line appears on a separate line because the line breaks are part of the template literal.

Multiline Strings Before ES6

Before template literals, you could use the newline escape sequence \n.

const message = "Welcome to JavaScript.\nLearn template literals.\nPractice with examples.";

console.log(message);

Output:

Welcome to JavaScript.
Learn template literals.
Practice with examples.

Both approaches work, but template literals are often easier to read when a string contains several lines.

Example: Creating a Multiline User Profile

const name = "Alex";
const city = "Hyderabad";
const profession = "Web Developer";

const profile = `Name: ${name}
City: ${city}
Profession: ${profession}`;

console.log(profile);

Output:

Name: Alex
City: Hyderabad
Profession: Web Developer

This example combines multiline strings with interpolation to generate a formatted profile.

Using Template Literals to Generate HTML

Template literals can make it easier to generate HTML strings containing dynamic data.

For example, you can create a simple product card:

const product = {
    name: "Laptop",
    price: 45000
};

const html = `
    <div class="product">
        <h2>${product.name}</h2>
        <p>Price: ₹${product.price}</p>
    </div>
`;

console.log(html);

Output:

<div class="product">
    <h2>Laptop</h2>
    <p>Price: ₹45000</p>
</div>

The template literal combines HTML markup with values from the product object.

This example creates an HTML string; it does not automatically display the HTML on a webpage. Also, do not insert untrusted user input into HTML without appropriate escaping or sanitization, because doing so can create cross-site scripting (XSS) vulnerabilities.

To learn more about working with objects, visit:

Template Literals vs String Concatenation

Template literals and string concatenation can both combine text with variables, but their syntax differs.

FeatureString ConcatenationTemplate Literals
SyntaxUses +Uses backticks
Insert variablesCombines values with +Uses ${}
Multiline stringsOften uses \n or concatenationSupports direct line breaks
ExpressionsCalculations are combined with +Expressions can appear inside ${}
ReadabilityCan become difficult with many valuesOften easier to read

Comparison Example

Using concatenation:

const item = "Book";
const price = 200;

console.log("The " + item + " costs ₹" + price + ".");

Using a template literal:

const item = "Book";
const price = 200;

console.log(`The ${item} costs ₹${price}.`);

Both examples produce the following output:

The Book costs ₹200.

Template literals are generally easier to maintain when strings contain multiple variables or expressions.

Common Mistakes When Using Template Literals

Using Quotation Marks Instead of Backticks

Template interpolation works with backticks, not ordinary single or double quotation marks.

Incorrect:

const name = "Alex";

console.log("Hello, ${name}!");

Output:

Hello, ${name}!

Correct:

const name = "Alex";

console.log(`Hello, ${name}!`);

Output:

Hello, Alex!

Forgetting the Dollar Sign

The interpolation syntax requires both $ and curly braces.

Incorrect:

const age = 25;

console.log(`Age: {age}`);

Output:

Age: {age}

Correct:

const age = 25;

console.log(`Age: ${age}`);

Output:

Age: 25

Confusing Template Literals with Automatic HTML Rendering

Template literals create strings. They do not automatically interpret the resulting string as HTML.

If you need to display content on a webpage, you must use an appropriate DOM method and handle untrusted content safely.

Frequently Asked Questions

What is a template literal in JavaScript?

A template literal is a string enclosed in backticks. It supports string interpolation, embedded expressions, and multiline strings.

What is string interpolation?

String interpolation is the process of inserting variables or expressions into a string. In JavaScript template literals, interpolation uses the ${} syntax.

What is the difference between a template string and a template literal?

The terms are often used interchangeably. Template literal is the standard term for the syntax that uses backticks to create strings with interpolation and multiline support.

Can template literals contain multiple lines?

Yes. Template literals preserve line breaks written directly inside the backticks.

Can I perform calculations inside template literals?

Yes. You can include expressions such as ${10 + 20} or ${price * quantity}.

Are template literals supported in modern browsers?

Yes. Template literals are supported by modern browsers and JavaScript runtimes. They were introduced in ES6.

What to Learn Next

Continue learning JavaScript ES6 features with these topics: