Template Literals

Introduction

Template Literals are a modern JavaScript feature introduced in ECMAScript 6 (ES6). They provide a more readable and flexible way to create strings compared to traditional string concatenation.

Template literals allow you to:

  • Embed variables directly inside strings.

  • Write multi-line strings without special characters.

  • Evaluate JavaScript expressions inside strings.

  • Create cleaner and more maintainable code.

For automation engineers, template literals are widely used for creating dynamic log messages, API URLs, XPath/CSS selectors, error messages, file paths, and test reports.


What are Template Literals?

A template literal is a string enclosed in backticks ( ) instead of single (' ') or double (" ") quotes.

It supports:

  • Variable interpolation

  • Expression evaluation

  • Multi-line strings


Syntax

`text`

With variables:

`Hello ${variable}`

With expressions:

`Result: ${expression}`

Why Do We Use Template Literals?

Template literals help developers:

  • Write cleaner code.

  • Avoid string concatenation.

  • Improve readability.

  • Easily create dynamic strings.

  • Handle multi-line text.


Creating a Template Literal

let message = `Welcome to JavaScript`;

console.log(message);

Output

Welcome to JavaScript

Variable Interpolation

Variables can be inserted directly using ${}.

let name = "John";

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

Output

Hello John

Multiple Variables

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

console.log(`Welcome ${firstName} ${lastName}`);

Output

Welcome John Doe

Using Expressions

JavaScript expressions can be evaluated inside ${}.

let a = 10;
let b = 20;

console.log(`Sum = ${a + b}`);

Output

Sum = 30

Calling Functions

Functions can also be used inside template literals.

function greet(name) {

    return `Hello ${name}`;

}

console.log(`${greet("Alice")}`);

Output

Hello Alice

Multi-line Strings

Without template literals:

let message =
"Welcome\n" +
"to\n" +
"JavaScript";

console.log(message);

Using template literals:

let message = `Welcome
to
JavaScript`;

console.log(message);

Output

Welcome
to
JavaScript

No \n characters are required.


Real-World Example

Suppose a website displays a welcome message after login.

let username = "Admin";

console.log(`Welcome ${username}!`);

Output

Welcome Admin!

Another example:

let product = "Laptop";
let price = 65000;

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

Output

Laptop costs ₹65000

Automation Testing Example

Automation engineers frequently generate dynamic log messages.

let testCase = "Login Test";

console.log(`Executing ${testCase}`);

Output

Executing Login Test

Example with API URLs:

let userId = 25;

let url = `https://api.example.com/users/${userId}`;

console.log(url);

Output

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

Example with Playwright:

let username = "admin";

console.log(`Logging in with user: ${username}`);

Output

Logging in with user: admin

Example with Selenium:

let browser = "Chrome";

console.log(`Running tests on ${browser}`);

Output

Running tests on Chrome

Template Literals vs String Concatenation

Using String Concatenation

let name = "John";

console.log("Hello " + name);

Using Template Literals

let name = "John";

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

The template literal version is shorter, cleaner, and easier to read.


Nested Expressions

You can use complex expressions inside ${}.

let marks = 75;

console.log(`Result: ${marks >= 35 ? "Pass" : "Fail"}`);

Output

Result: Pass

Using Object Properties

const student = {

    name: "Rahul",
    age: 22

};

console.log(`${student.name} is ${student.age} years old.`);

Output

Rahul is 22 years old.

Common Mistakes

Using Single Quotes Instead of Backticks

Incorrect:

let name = "John";

console.log('Hello ${name}');

Output

Hello ${name}

The variable is not replaced because single quotes do not support interpolation.

Correct:

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

Forgetting ${}

Incorrect:

let age = 25;

console.log(`Age: age`);

Correct:

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

Using Quotes Instead of Backticks

Incorrect:

"Welcome ${name}"

Correct:

`Welcome ${name}`

Best Practices

Prefer Template Literals Over Concatenation

Instead of:

console.log("Hello " + username);

Use:

console.log(`Hello ${username}`);

Use Meaningful Variable Names

Template literals become easier to understand when variables have descriptive names.


Keep Expressions Simple

Avoid placing overly complex logic inside ${}.

Instead of:

`${a > b ? calculateValue(a, b) : anotherFunction()}`

Store the result in a variable first for better readability.


Use Template Literals for Dynamic Strings

They are ideal for:

  • URLs

  • Log messages

  • HTML snippets

  • SQL queries

  • API endpoints

  • Email templates


Conclusion

Template literals provide a modern, readable, and efficient way to work with strings in JavaScript. They eliminate the need for cumbersome string concatenation and make it easy to include variables, expressions, and multi-line text.

For automation engineers, template literals are especially valuable when creating dynamic API URLs, logging execution details, generating reports, and building reusable automation scripts.


Frequently Asked Questions (FAQs)

What are template literals in JavaScript?

Template literals are strings enclosed in backticks ( ) that support variable interpolation, expressions, and multi-line text.


What is the syntax of a template literal?

`Hello ${name}`

What is variable interpolation?

Variable interpolation is the process of inserting variable values directly into a string using ${}.

Example:

let name = "John";

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

Why are template literals better than string concatenation?

They improve readability, reduce code complexity, and make dynamic strings easier to create and maintain.


Why are template literals useful in automation testing?

Automation engineers use template literals to create dynamic API endpoints, log messages, file paths, selectors, SQL queries, and test reports, making automation scripts cleaner and more maintainable.


Key Takeaways

  • Template literals use backticks ( ) instead of single or double quotes.

  • Variables are inserted using ${}.

  • JavaScript expressions can be evaluated inside ${}.

  • Multi-line strings are supported without using \n.

  • Template literals improve code readability.

  • They are preferred over string concatenation.

  • They are widely used for dynamic strings in modern JavaScript.

  • Automation engineers use them for API URLs, logs, reports, and selectors.

  • Avoid using single quotes when interpolation is required.

  • Mastering template literals is essential for writing clean, modern JavaScript code.