JavaScript Template Literals: Backtick Strings
Building strings with + gets noisy quickly: "Hi " + name + ", you have " + count + " items". Template literals, written with backticks, let you place values directly inside the text with ${...}.
Interpolation
Anything inside ${ } is a JavaScript expression. It is evaluated, converted to a string and inserted. Variables, arithmetic, method calls and ternary expressions all work. In the example, ${(items * price).toFixed(2)} calculates the total and formats it with exactly two decimals.
Notice the $${...} in the total line. The first $ is ordinary text, the dollar sign of the price; only a $ followed by { starts an expression. To write a literal backtick inside a template, escape it as \`.
Expected output
Liam ordered 3 books. Total: $37.50 Status: free shipping Order for Liam - 3 x Paper Cranes 1 + 1 = 2 single double
Multi-line strings
A template literal can span several lines; the line breaks and the indentation become part of the string. That is convenient for small blocks of text, but keep in mind that the leading spaces of the second line are included exactly as typed, as the receipt in the output shows.
Formatting numbers
Template literals insert values as-is, so format numbers yourself:
n.toFixed(2)returns a string with two decimals, rounding as needed.n.toLocaleString("en-US")adds thousands separators, as in1,234,567.String(n).padStart(3, "0")zero-pads.
When to use which quotes
Many teams use backticks only when they interpolate or need multiple lines, and plain quotes everywhere else. That is a style choice; the language treats a template without ${} exactly like an ordinary string.
Template literals can also be tagged, as in html`<p>${text}</p>` , where a function processes the pieces. Libraries use tags for safe HTML and SQL building; you will rarely write one yourself as a beginner.
Common mistakes
- Using single or double quotes with
${}: the braces are printed literally. - Putting objects inside
${}and getting[object Object]. Insert specific properties, or convert withJSON.stringify(). - Concatenating user input into HTML with templates. Insert text with
textContentinstead to avoid injection.
Summary
- Backtick strings embed expressions with
${expression}. - They can span multiple lines, including the indentation.
- Format numbers with
toFixed()ortoLocaleString()before inserting.
Quiz: Template literals