Building HTML by joining many quoted strings gets hard to read. A template literal lets the markup span lines while putting values where they belong. Write it between backticks (`), rather than quotes. Like an ordinary string literal, it produces a string. section 7.0 section 7.1
Three features make the syntax useful:
- Interpolation: `${expression}` evaluates an expression and inserts its value. For example, `You have ${cart.length} items` uses the cart’s current length instead of joining separate strings with `+`. section 7.1
- Multiline text: the literal itself can cross line breaks. This differs from writing `\n` inside a single-line quoted string. section 7.1
- Tagging: a function placed before the backtick receives the string parts and substituted values separately. It can process them and return a string or another value; interpolation alone does not provide that processing. section 7.1
function getProductHTML(product) {
return `
<div class="product">
<div class="product-image">
<img alt="${product.name}" src="${product.image_url}">
</div>
<div class="product-desc">${product.desc}</div>
</div>
`;
}
Follow the product markup from top to bottom: its lines remain together, while `${product.name}`, `${product.image_url}`, and `${product.desc}` supply the varying content. section 7.1
Despite its name, a template literal is not a reusable template. `let greeting = `Hello, ${name}`` creates a string immediately; changing `name` later does not update it. For a fresh string each time, put the literal in a function: `function greet(name) { return `Hello, ${name}`; }`. section 7.2
Try converting a string-concatenating greeting or HTML fragment to a template literal. Then make it reusable with a function. As a further exercise, write a tag that converts interpolated objects to key/value pairs before inserting them. section 7.1 section 7.2 section 7.4


