What is a template literal in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
${expression} placeholders. JavaScript evaluates each placeholder and puts the result into the string, and the string may span several lines.This answer is one piece of Chapter 1: Values and Variables.
Tests build strings all the time: a URL with a seed, a selector with a SKU, an expected message with a price. Joining those with + is easy to get wrong, because one missing space or quote breaks the string. A template literal lets you write the finished string and drop values into it.
In the example, sku and priceInr are ordinary variables. The locator is built with `article[data-sku="${sku}"]`, so the double quotes the CSS selector needs sit inside the backticks without any escaping. The expected text is `₹${priceInr.toLocaleString('en-IN')}`: a placeholder can hold any expression, here a method call that formats 11900 as 11,900. The assertion then checks the grinder card shows ₹11,900.
Only backticks do this. Write 'Total: ${qty}' in single quotes and you get those characters literally, ${qty} and all, which is a common reason a test compares against the wrong text. If an expected message looks right in the code but fails with a $ in the received value, check the quote marks first.
import { test, expect } from '@playwright/test';
test('one template literal builds the locator and the expected price', async ({ page }) => {
await page.goto('/catalog.html?mock=static&seed=42&autologin=1');
const sku = 'MRD-1003';
const priceInr = 11900;
const card = page.locator(`article[data-sku="${sku}"]`);
await expect(card.getByTestId('product-price')).toHaveText(`₹${priceInr.toLocaleString('en-IN')}`);
});1 passed (2.8s)
const qty = 3, what does console.log('Total: ${qty}') print?Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free