Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 7 of 58

Template literals

Build strings with backticks, insert values and expressions with ${}, write multi-line text, and learn when template literals beat plain concatenation.

9 minGetting startedUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite template literals that mix text with variables and expressions, create multi-line strings, and avoid the common backtick mistakes.

After this lesson you can build text from variables without a pile of plus signs, write text that spans several lines, and put small calculations directly inside a sentence.

The old way and the better way

You already know that + joins strings.

javascript
const name = "Asha";
const n = 3;
console.log("Hi " + name + ", " + n + " items");

That prints Hi Asha, 3 items. It works, but the quotes, spaces and plus signs add up, and one missing space spoils the output. A template literal does the same job more clearly. Wrap the text in backticks (the key under Escape on most keyboards) and put values inside ${ }.

javascript
const name = "Asha";
const n = 3;
console.log(`Hi ${name}, ${n} items`);   // Hi Asha, 3 items

The text reads like the sentence it produces, and the spaces are exactly what you typed.

Any expression works

What goes inside ${ } is not limited to variable names. It can be any expression: arithmetic, a method call, or a condition.

javascript
const name = "Asha", n = 3, price = 4.5;
console.log(`Hi ${name}, you have ${n} item${n === 1 ? "" : "s"}. Total: ${(n * price).toFixed(2)}`);
// Hi Asha, you have 3 items. Total: 13.50

Here a small test adds an "s" only when needed, and toFixed formats the money. The expression is evaluated, converted to a string, and inserted. Keep what you place inside short. If it needs more than a line, calculate it above, give it a name, and insert the name.

Multi-line strings

A normal string cannot contain a raw line break. A template literal can, and the break becomes part of the text.

javascript
const poem = `Roses are red,
Violets are blue.`;
console.log(poem);

That prints two lines. This is very useful for blocks of HTML. Be careful with indentation: spaces at the start of the continued lines are part of the string too.

See it work

Change the name, count and price and watch the sentence follow.

html
<p id="out"></p>
<script>
  const customer = "Asha";
  const items = 3;
  const price = 4.5;

  const total = items * price;
  const sentence = `${customer} ordered ${items} item${items === 1 ? "" : "s"}.
Total: $${total.toFixed(2)}`;

  document.getElementById("out").innerHTML = sentence.replace("\n", "<br>");
</script>

Spot the $${total...} near the end: the first $ is a plain dollar sign, and ${ } after it is the placeholder. A $ only starts a placeholder when it is directly followed by {. Also notice that HTML ignores a raw line break, so the example swaps it for a <br> tag to show it.

What gets inserted

Whatever is inside the braces is converted to a string. For numbers and booleans that is what you expect. For other values it can surprise you.

javascript
console.log(`${1 + 1} ${"x".toUpperCase()} ${[1, 2, 3]} ${{}} ${null} ${undefined}`);
// 2 X 1,2,3 [object Object] null undefined
  • An array becomes its items joined by commas.
  • A plain object becomes [object Object], which is almost never what you want. Use JSON.stringify(obj) to see its content.
  • null and undefined become the words null and undefined. If you see undefined in your output, a variable was empty.

Escaping

To show a backtick or the exact characters ${, put a backslash before them.

javascript
console.log(`Price: \${5}`);   // Price: ${5}
console.log(`back\`tick`);     // back`tick

A word about tagged templates

You can place a function name directly before a template literal, as in tag followed by a backtick string. The function then receives the pieces and the values separately. This powers some libraries for styling and database queries. It is an advanced feature and you do not need it now.

When to use which

Use a template literal whenever you mix text with values, or need several lines. Use a plain quoted string for a fixed piece of text with no values. Many teams also use plain quotes for short constants and reserve backticks for places where they are needed, so a backtick tells the reader "something is inserted here". Either way, be consistent.

Building pieces of HTML

A frequent use of template literals on the web is making a block of HTML from data. Because the text can span lines and hold values, the code looks very much like the markup it creates. Later in the course you will put such text into a page. One warning for then: if a value comes from a visitor, inserting it as HTML can let them add their own markup, so treat user-supplied text carefully and prefer setting textContent. For now it is enough to know that the same ${ } placeholder that builds a sentence also builds markup, a message for the console, or a line of a report.

Common mistakes

  • Using quotes instead of backticks. "Hi ${name}" prints the placeholder as text. Check the quote character first.
  • Writing $name or {name}. The placeholder needs both the dollar sign and the braces: ${name}.
  • Letting undefined appear. If a sentence shows undefined, the variable was never set or the name is wrong.
  • Putting long logic inside ${ }. It becomes unreadable. Move it to a variable above.
  • Forgetting indentation is included. In a multi-line literal, leading spaces end up in the output.
  • Inserting an object directly. [object Object] means you needed a property such as user.name.

Exercise

  1. Create variables product, qty and unitPrice. Print one sentence such as "3 x Notebook = 13.50", built with a single template literal and toFixed(2).
  2. Make it say "1 item" or "2 items" correctly using a conditional expression inside the placeholder.
  3. Use a multi-line template literal to make a three-line address, and print it.

Next: Operators.

Key points

  • A template literal is text wrapped in backticks that can contain ${expression} placeholders.
  • Any expression can go inside ${}, and its result is converted to a string.
  • Template literals can span several lines, and the line breaks become part of the text.
  • null, undefined, arrays and objects convert in ways that may surprise you, such as [object Object].
  • Escape a literal backtick or ${ with a backslash.

Check yourself

1. Which line correctly inserts the variable name into a string?
2. What does `${2 + 3}` produce?
3. What does `${{}}` insert into the text?
4. How do you include a backtick inside a template literal?

Free tools for this lesson