JavaScript Template Literals
Table of Contents + β
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.
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.oldGreetingbuilds the sentence with+, splitting it into three pieces aroundname.greetingwrites 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.
const price = 20;const qty = 3;
console.log(`Total: $${price * qty}`); // Total: $60console.log(`Items: ${qty + 1}`); // Items: 4console.log(`Name: ${"alex".toUpperCase()}`); // Name: ALEXHere is what each line produces:
- The first
console.logdoes the mathprice * qtyinside the braces and prints60. The extra$outside the braces is just the dollar sign in the text. - The second runs
qty + 1and prints4. - The third calls
"alex".toUpperCase()and printsALEX.
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.
// β Old way: manual \n line breaksconst oldNote = "Line one\nLine two\nLine three";
// β
New way: real line breaksconst note = `Line oneLine twoLine three`;
console.log(note);// Line one// Line two// Line threeLetβs compare the two approaches:
oldNotepacks everything on one line and uses\nto mark each break.noteis 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.
const user = { name: "Alex", role: "Admin", points: 1250 };
// β Hard to read with concatenationconst cardOld = "<div class='card'>" + "<h2>" + user.name + "</h2>" + "<p>" + user.role + " β " + user.points + " pts</p>" + "</div>";
// β
Clear with a multi-line template literalconst 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:
userholds the three values we want to show: the name, the role, and the points.cardOldbuilds the HTML with+, breaking it into many small pieces around each value.cardwrites 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!
- Create a
namevariable and print a greeting using a template literal. - Make
priceandqtyvariables, then print the total with${price * qty}. - Write a multi-line address as a single template literal and log it.
- 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.