JavaScript Template Literals

In the previous lesson, we learned how to respond to user actions with DOM events. Now let’s look at a cleaner way to build strings using template literals.

πŸͺΆ What are Template Literals?

A template literal is a string written with backticks instead of quotes. Inside it you can drop variables and expressions directly using ${ }, so you no longer have to glue pieces together with the + operator.

Here is the same greeting written the old way and the new way.

template-literals.js
const name = "Alex";
// ❌ Old way: string concatenation with +
const oldGreeting = "Hello, " + name + "! Welcome back.";
// βœ… New way: template literal with ${ }
const greeting = `Hello, ${name}! Welcome back.`;
console.log(greeting); // Hello, Alex! Welcome back.

Let’s walk through what each line does:

  • const name = "Alex" stores the value we want to drop into the sentence.
  • oldGreeting builds the sentence with +, splitting it into three pieces around name.
  • greeting writes the whole sentence in backticks and places ${name} right where the value belongs.
  • console.log(greeting) prints the finished sentence.

The backtick version reads almost like the finished sentence. The variable name sits right where its value belongs, and there are no quotes or plus signs to track.

Feature Concatenation (+) Template literal
Wrapping character " or ' ` (backtick)
Insert a variable "Hi " + name `Hi ${name}`
Multiple lines Needs \n Just press Enter

πŸ’² Embedding Expressions with $

Whatever you put between ${ and } is treated as a JavaScript expression. JavaScript runs it, turns the result into text, and slots it into the string. That means you are not limited to plain variables, you can use any expression.

template-literals.js
const price = 20;
const qty = 3;
console.log(`Total: $${price * qty}`); // Total: $60
console.log(`Items: ${qty + 1}`); // Items: 4
console.log(`Name: ${"alex".toUpperCase()}`); // Name: ALEX

Here is what each line produces:

  • The first console.log does the math price * qty inside the braces and prints 60. The extra $ outside the braces is just the dollar sign in the text.
  • The second runs qty + 1 and prints 4.
  • The third calls "alex".toUpperCase() and prints ALEX.

The same trick works for calling methods, reading object properties, or any other expression that produces a value.

πŸ“„ Multi-Line Strings

With backticks, a string can span several lines exactly as you type it. Every line break you add becomes part of the string, so you never need the \n escape.

template-literals.js
// ❌ Old way: manual \n line breaks
const oldNote = "Line one\nLine two\nLine three";
// βœ… New way: real line breaks
const note = `Line one
Line two
Line three`;
console.log(note);
// Line one
// Line two
// Line three

Let’s compare the two approaches:

  • oldNote packs everything on one line and uses \n to mark each break.
  • note is written across three real lines, and each Enter you press becomes a line break in the string.
  • console.log(note) prints the three lines exactly as they appear in the code.

Great for blocks of text

Multi-line template literals are perfect for emails, addresses, and any text that has a natural shape, because what you write is what you get.

🧱 A Practical Example

Template literals shine when you build a chunk of HTML or a message from several variables at once. Compare the two versions below.

template-literals.js
const user = { name: "Alex", role: "Admin", points: 1250 };
// ❌ Hard to read with concatenation
const cardOld =
"<div class='card'>" +
"<h2>" +
user.name +
"</h2>" +
"<p>" +
user.role +
" β€” " +
user.points +
" pts</p>" +
"</div>";
// βœ… Clear with a multi-line template literal
const card = `
<div class="card">
<h2>${user.name}</h2>
<p>${user.role} β€” ${user.points} pts</p>
</div>
`;
console.log(card);

Here is what this code is doing:

  • user holds the three values we want to show: the name, the role, and the points.
  • cardOld builds the HTML with +, breaking it into many small pieces around each value.
  • card writes the same HTML across real lines, dropping each value in with ${user.name}, ${user.role}, and ${user.points}.
  • console.log(card) prints the finished HTML block.

The template literal keeps the HTML structure visible, and each ${ } shows exactly where a value goes. Adding another field is a one-line change instead of a hunt through plus signs and quotes.

⚠️ Common Mistakes to Avoid

Mistake Problem Solution
Using normal quotes instead of backticks "Hi ${name}" prints the text ${name} literally Wrap the string in backticks `
Forgetting the $ before the braces `Hi {name}` prints {name} as plain text Always write ${ }, never just { }
Cramming heavy logic inside ${ } Long expressions make the string hard to read Compute the value first, then drop the variable in

Keep ${ } simple

A template literal is for placing values into text, not for writing programs. If an expression grows long, store it in a variable above and reference that variable inside the braces.

πŸ”§ Try It Yourself!

  1. Create a name variable and print a greeting using a template literal.
  2. Make price and qty variables, then print the total with ${price * qty}.
  3. Write a multi-line address as a single template literal and log it.
  4. Take a string that uses + concatenation and rewrite it with backticks.

🧩 What You’ve Learned

  • βœ… Template literals are strings written with backticks `
  • βœ… ${ } embeds variables and any expression directly in the string
  • βœ… Backtick strings can span multiple lines without \n
  • βœ… They replace messy + concatenation with readable text
  • βœ… Keep the code inside ${ } short and simple

πŸš€ What’s Next?

Now that your strings are clean, we will make functions easier to call with sensible fallbacks. Let’s continue to Default Parameters.

Share & Connect