Template Literals

Introduction

Template literals are a modern JavaScript feature introduced in ES6 (ECMAScript 2015) that provide a more powerful and readable way to work with strings.

Unlike traditional strings created with single (' ') or double (" ") quotes, template literals are enclosed in backticks (`). They support features such as string interpolation, multi-line strings, and embedded expressions, making string creation much simpler and cleaner.

Template literals are widely used in modern JavaScript applications, Node.js, React, and automation frameworks such as Selenium, Playwright, and Cypress. They are especially useful when constructing dynamic messages, URLs, XPath expressions, CSS selectors, API requests, and log messages.


What are Template Literals?

A template literal is a string enclosed in backticks (`).

It allows you to:

  • Embed variables directly into strings.

  • Evaluate JavaScript expressions.

  • Create multi-line strings.

  • Improve code readability.


Syntax

`Text goes here`

String Interpolation Syntax

Variables and expressions can be inserted using ${}.

`${expression}`

Why Do We Use Template Literals?

Template literals help developers:

  • Create dynamic strings.

  • Avoid complex string concatenation.

  • Write multi-line strings easily.

  • Improve code readability.

  • Embed variables and expressions directly into text.


Creating a Template Literal

let language = `JavaScript`;

console.log(language);

Output

JavaScript

Using Variables

let name = "John";

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

Output

Welcome John

Embedding Multiple Variables

let firstName = "John";

let lastName = "Doe";

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

Output

Employee: John Doe

Using Expressions

Template literals can evaluate JavaScript expressions.

let a = 10;

let b = 20;

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

Output

Sum = 30

Multi-Line Strings

Backticks allow strings to span multiple lines without special characters.

let address = `Bengaluru
Karnataka
India`;

console.log(address);

Output

Bengaluru
Karnataka
India

Calling Functions Inside Template Literals

function greet(name) {

    return `Hello ${name}`;

}

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

Output

Hello Alice

Using Conditional Expressions

let age = 20;

console.log(`${age >= 18 ? "Adult" : "Minor"}`);

Output

Adult

Real-World Example

Suppose an online shopping application displays order information.

let customer = "John";

let orderId = 1025;

console.log(`Customer ${customer} placed Order #${orderId}`);

Output

Customer John placed Order #1025

Another example:

let product = "Laptop";

let price = 55000;

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

Output

Laptop costs ₹55000

Automation Testing Example

Automation engineers frequently use template literals to create dynamic URLs, locators, log messages, test data, and API requests.

Playwright Example

Open a dynamic URL.

const userId = 101;

await page.goto(`https://example.com/users/${userId}`);

Selenium Example

Create a dynamic XPath.

const userName = "Admin";

const xpath = `//td[text()="${userName}"]`;

const element = await driver.findElement(By.xpath(xpath));

Cypress Example

Generate a dynamic URL.

const pageName = "dashboard";

cy.visit(`https://example.com/${pageName}`);

API Testing Example

Create a dynamic API endpoint.

const userId = 15;

const endpoint = `https://api.example.com/users/${userId}`;

console.log(endpoint);

Output

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

Data-Driven Testing Example

Display usernames.

const users = [

    "admin",

    "manager",

    "tester"

];

for (const user of users) {

    console.log(`Executing tests for ${user}`);

}

Output

Executing tests for admin
Executing tests for manager
Executing tests for tester

Traditional Concatenation vs Template Literals

Using String Concatenation

let name = "John";

console.log("Welcome " + name);

Output

Welcome John

Using Template Literals

let name = "John";

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

Output

Welcome John

Template literals are cleaner and easier to read.


Common Mistakes

Using Quotes Instead of Backticks

Incorrect:

let name = "John";

console.log("Welcome ${name}");

Output

Welcome ${name}

${} only works inside backticks, not single or double quotes.

Correct:

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

Forgetting ${}

Incorrect:

let age = 25;

console.log(`Age = age`);

Output

Age = age

Correct:

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

Unnecessary Concatenation

Instead of:

let city = "Delhi";

console.log("City: " + city);

Use:

console.log(`City: ${city}`);

Best Practices

Prefer Template Literals for Dynamic Strings

Use template literals whenever variables or expressions are included in a string.


Use Backticks Only When Needed

For simple static strings, single or double quotes are acceptable.


Keep Expressions Simple

Avoid writing very complex logic inside ${}.


Use Meaningful Variable Names

Instead of:

let x = "John";

Use:

let employeeName = "John";

This improves readability.


Conclusion

Template literals provide a modern, readable, and efficient way to create strings in JavaScript. Their support for string interpolation, multi-line strings, and embedded expressions makes them superior to traditional string concatenation for most use cases.

For automation engineers, template literals are invaluable for constructing dynamic URLs, XPath expressions, CSS selectors, API endpoints, log messages, and test data. Mastering template literals will help you write cleaner, more maintainable, and more professional JavaScript automation scripts.


Frequently Asked Questions (FAQs)

What are template literals in JavaScript?

Template literals are strings enclosed in backticks that support string interpolation, multi-line text, and embedded expressions.


What is the syntax of a template literal?

`Hello World`

How do you insert a variable into a template literal?

Use ${}.

`Welcome ${name}`

Can template literals span multiple lines?

Yes. Backticks allow strings to be written across multiple lines without special escape characters.


Why are template literals useful in automation testing?

Automation engineers use template literals to build dynamic URLs, XPath expressions, CSS selectors, API endpoints, log messages, and test data, making automation scripts cleaner and easier to maintain.


Key Takeaways

  • Template literals were introduced in ES6.

  • They are enclosed in backticks (`).

  • Variables and expressions are embedded using ${}.

  • They support multi-line strings.

  • They eliminate the need for complex string concatenation.

  • They improve code readability and maintainability.

  • They are ideal for creating dynamic strings.

  • They are widely used in modern JavaScript applications and automation frameworks.

  • They simplify the creation of URLs, locators, API endpoints, and log messages.

  • Mastering template literals is essential for writing clean and professional JavaScript code.