Introduction
In our previous lesson, we explored type coercion and saw how JavaScript's automatic type conversions can sometimes lead to confusing behavior, especially when using the + operator to join strings and numbers. You learned that '10' + 5 results in the string '105', not the number 15. This method of building strings, called concatenation, can become clumsy and error-prone.
Today, we'll learn a modern, powerful, and much more readable way to create dynamic strings in JavaScript: template literals. This lesson will teach you how to use them to embed variables and expressions directly into a string, a technique you'll use constantly when writing test automation scripts to create clear log messages, dynamic element selectors, and informative test assertions.
From Concatenation Chaos to Template Clarity
Before we dive into the new syntax, let's visualize the problem we're trying to solve. In the past, if you wanted to construct a sentence using variables, you had to "add" strings and variables together. This often resulted in a messy mix of quotes and plus signs, making the code hard to read and easy to break.
For example, imagine creating a summary message from a user's data:
// The old way: String concatenation with '+'
const user = {
name: 'Alex',
role: 'Developer',
lang: 'JavaScript'
};
const message = 'Hello, ' + user.name + ', you are a ' + user.role + ' who loves ' + user.lang + '!';
console.log(message);
// Output: Hello, Alex, you are a Developer who loves JavaScript!
Notice how easy it would be to forget a space before a variable or miss a closing quote. This is a common source of small but frustrating bugs.

As the image shows, template literals offer a much cleaner path. Let's learn how they work.
Your First Template Literal
Template literals, introduced in the ES6 version of JavaScript, provide a new way to define strings that solves the problems of concatenation. There are two key differences:
- They use backticks (
`) instead of single (' ') or double (" ") quotes. The backtick key is usually located below theEsckey on your keyboard. - They can contain placeholders to embed expressions directly into the string.
The following video from Programming with Mosh provides an excellent introduction. It starts by highlighting the exact problems we just discussed and then demonstrates how template literals elegantly solve them.
Watch this video to understand the fundamental benefits of template literals.
The first part explains the issues with traditional strings, especially for creating multi-line text and escaping quotes. The next section shows how template literals using backticks simplify multi-line strings and make the code cleaner. Finally, watch the explanation of placeholders (${...}), which is the most powerful feature of template literals.
String Interpolation: The Core Concept
As you saw in the video, the ability to embed expressions directly into a string is called string interpolation. This is done using the ${expression} syntax within a template literal.
Let's break down the rules and capabilities of this feature by consulting the official MDN documentation, which is the most authoritative resource for web developers.
Template literals (Template strings) - JavaScript | MDN
This document provides a comprehensive overview of template literals. We will focus on the most common and essential features.
First, familiarize yourself with the basic syntax. Next, read the section on multi-line strings and string interpolation. Pay close attention to the "before" and "after" code examples that compare concatenation with the ${expression} syntax. This is the heart of today's lesson. The article notes that template literals "coerce their expressions directly to strings," which is a direct link back to our previous lesson on type coercion!
Let's rewrite our initial example using a template literal. The improvement in readability is immediately obvious.
// The modern way: Template literal
const user = {
name: 'Alex',
role: 'Developer',
lang: 'JavaScript'
};
const message = `Hello, ${user.name}, you are a ${user.role} who loves ${user.lang}!`;
console.log(message);
// Output: Hello, Alex, you are a Developer who loves JavaScript!
What Can Go Inside ${...}?
The expression inside a placeholder can be more than just a simple variable. It can be any valid JavaScript expression that produces a value. This makes template literals incredibly versatile.
Here are a few examples that are particularly relevant for test automation:
1. Arithmetic Operations:
You can perform calculations directly within the string. This is useful for verifying calculations in an application.
const price = 19.99;
const quantity = 3;
const taxRate = 0.07;
const confirmationMsg = `Your total for ${quantity} items is $${(price * quantity * (1 + taxRate)).toFixed(2)}.`;
console.log(confirmationMsg);
// Output: Your total for 3 items is $64.17.
(Note: .toFixed(2) is a method we'll cover later; for now, just know it formats the number to two decimal places.)
2. Function Calls:
You can call a function and embed its return value.
function getTimestamp() {
return new Date().toLocaleTimeString();
}
console.log(`Test started at: ${getTimestamp()}`);
// Output: Test started at: 3:30:15 PM (will vary)
3. Conditional Logic (Ternary Operator):
You can even use conditional logic to change the string's content on the fly.
const itemsInCart = 5;
const cartStatus = `You have ${itemsInCart} item${itemsInCart === 1 ? '' : 's'} in your cart.`;
console.log(cartStatus);
// Output: You have 5 items in your cart.
// Try changing itemsInCart to 1 and see what happens!
For more examples of what you can embed in a template literal, the GeeksforGeeks article provides a concise list.
JavaScript Template Literals - GeeksforGeeks
This article gives several practical examples. You can quickly scan through them to see the variety of expressions you can use.
Focus on the examples for Conditionals in Templates and Embedding Functions. These demonstrate how you can embed more than just simple variables.
As a QA engineer, you will constantly be creating dynamic strings for logging, reporting, and interacting with web elements. For example, you might need to click on a button that has a user's name in it, or verify that an error message contains the correct transaction ID. Template literals make these tasks straightforward and robust.
Conclusion
You have now learned how to move from cumbersome string concatenation to clean, modern template literals. This is a small syntactic change, but it has a huge impact on code quality and readability.
Key Takeaways:
- Template literals are defined with backticks (
`). - They allow for multi-line strings without needing special characters like
\n. - The most powerful feature is string interpolation, using the
${expression}syntax to embed dynamic values. - The expression inside a placeholder can be anything that produces a value: a variable, a calculation, a function call, or even conditional logic.
- This feature is essential for writing clear and maintainable test automation code.
In our lessons so far, you've been using console.log() to see the output of your code snippets. In the next lesson, we'll formally cover this function and explore how it becomes your most fundamental tool for inspecting values and debugging logical errors in your programs.