Template Literals
Template literals are strings written with backticks. They can embed any expression with ${…}, span multiple lines without escape characters, and even be processed by a function. They've largely replaced + concatenation in modern code.
Interpolation
const name = "Sam"; const items = 3; const price = 4.5; console.log("Hi " + name + ", you have " + items + " items."); console.log(`Hi ${name}, you have ${items} items.`); console.log(`Total: $${(items * price).toFixed(2)}`);
Hi Sam, you have 3 items. Hi Sam, you have 3 items. Total: $13.50
Anything inside ${ } is evaluated as JavaScript and converted to a string: variables, arithmetic, function calls, even ternaries. The $ before ${ in the last line is just a literal dollar sign.
Expressions inside
const score = 72; const user = { first: "Lin", last: "Park" }; const tags = ["js", "web"]; console.log(`Result: ${score >= 50 ? "pass" : "fail"}`); console.log(`Name: ${user.first} ${user.last.toUpperCase()}`); console.log(`Tags: ${tags.join(", ")}`); console.log(`Now: ${new Date(0).toISOString().slice(0, 4)}`);
Result: pass Name: Lin PARK Tags: js, web Now: 1970
Keep interpolations short. If an expression gets complicated, compute it into a well-named variable first.
Multi-line strings
Line breaks inside backticks are kept as-is:
const poem = `Roses are red, Violets are blue, Template literals Are handy for you.`; console.log(poem);
Roses are red, Violets are blue, Template literals Are handy for you.
Be aware that indentation is kept too — if you indent the lines inside your code, those spaces become part of the string.
Building HTML
Template literals make it easy to generate HTML from data:
innerHTML with data you control, or escape it first. For user content, set textContent on elements you create (lesson 43).Tagged templates
A function name placed directly before a template literal receives the literal's pieces and values separately, and can return anything. This is how libraries implement safe SQL queries, CSS-in-JS and translation:
function highlight(strings, ...values) { return strings.reduce((out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""), ""); } const item = "coffee"; const qty = 2; console.log(highlight`Ordered ${qty} cups of ${item}.`);
Ordered [2] cups of [coffee].
strings is the array of literal text parts (["Ordered ", " cups of ", "."]) and values holds the interpolated values. You won't write tag functions often, but you'll recognise them in libraries.
String.raw
The built-in tag String.raw ignores escape sequences — handy for Windows paths and regular expressions:
console.log(`C:\new\table`.length > 0 ? "escapes processed" : ""); console.log(String.raw`C:\new\table`);
escapes processed C:\new\table