Hello readers π, welcome to 13th blog of this JavaScript series!
Today I want to talk about something that completely changed how I write strings in JavaScript - Template Literals. Once you start using them, there's no going back.
If you've ever struggled to build a dynamic message by gluing strings and variables together with + signs, you know the pain. Template literals make that whole process cleaner, more readable, and honestly, a lot more fun.
Let me walk you through everything you need to know.
The pain of traditional string concatenation
Before ES6, if you wanted to create a string that included variables, you had to break out of quotes, add +, then add the variable, then another +, then more quotes. It looked something like this:
const name = "Satya";
const age = 21;
const city = "Delhi";
const message = "Hi, I'm " + name + ". I am " + age + " years old and I live in " + city + ".";
console.log(message);
// Hi, I'm Satya. I am 21 years old and I live in Delhi.
Now imagine doing this for a bunch of lines or with multiple conditions. It gets messy real quick. Some common problems:
- Forgetting a space leads to words getting joined incorrectly.
- Too many
+and quotes make the line hard to read. - Multi-line strings are not supported directly - you'd need
\nescape characters. - Adding expressions like
${price * quantity}is impossible; you'd have to calculate separately and then concatenate.
Basically, the old way works but it's like building a sentence by cutting words out of a newspaper. Clunky.
Enter Template Literals
Template literals are defined using backticks ( ` ) instead of single or double quotes. They allow you to embed variables and expressions directly inside the string using ${}.
Syntax:
`string text ${expression} string text`
That's it. Let's rewrite the earlier example:
const name = "Satya";
const age = 22;
const city = "Jaipur";
const message = `Hi, I'm ${name}. I am ${age} years old and I live in ${city}.`;
console.log(message);
// Hi, I'm Satya. I am 22 years old and I live in Jaipur.
Right away, it's so much cleaner. No more + operators breaking the flow. You can read the string just like a normal sentence, with variables inserted where they belong.
Embedding variables (and more)
The ${} placeholder is not limited to just variable names. You can put any valid JavaScript expression inside it - arithmetic, function calls, ternary operators, you name it.
const a = 10;
const b = 5;
console.log(`Sum: ${a + b}`); // Sum: 15
console.log(`Comparison: ${a > b}`); // Comparison: true
console.log(`Uppercase: ${"hello".toUpperCase()}`); // Uppercase: HELLO
const isLoggedIn = true;
console.log(`Welcome ${isLoggedIn ? "back" : "guest"}!`);
// Welcome back!
This means you no longer have to break out of the string, compute something, store it in a temp variable, and then concatenate. Everything stays inside the string, respecting the visual flow.
Multi-line strings become effortless
Another huge pain point with regular quotes was writing multi-line strings. Previously, you'd do:
const poem = "Roses are red,\n" +
"Violets are blue,\n" +
"JavaScript is fun,\n" +
"And so are you.";
With template literals, you just press Enter:
const poem = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you.`;
The line breaks are preserved exactly as you type them. This is a game-changer when you need to generate HTML templates, email bodies, or any kind of formatted text in your code. No more \n nightmares.
Before vs after - a side-by-side visual
Let's take a real-world scenario: building a dynamic HTML card using JavaScript.
Old way (string concatenation):
const title = "My Blog";
const author = "Satya";
const posts = 12;
const card = '<div class="card">' +
'<h2>' + title + '</h2>' +
'<p>by ' + author + '</p>' +
'<span>' + posts + ' posts</span>' +
'</div>';
It's a mess of quotes and + signs. You can easily miss a closing quote or a space.
New way (template literal):
const card = `
<div class="card">
<h2>${title}</h2>
<p>by ${author}</p>
<span>${posts} posts</span>
</div>
`;
That's night and day. The structure is clear, the values are injected directly, and it actually looks like the HTML you're generating. Readability improves dramatically.
Use cases in modern JavaScript
Template literals aren't just for simple variable injection. You'll see them everywhere in modern code.
1. Generating HTML (as shown above)
Frameworks like React use JSX, but even in vanilla JS, building small UI snippets is a breeze.
2. Dynamic CSS styling strings
For inline styles or CSS-in-JS, you can embed values:
const size = 16;
const style = `font-size: ${size}px; color: ${isActive ? 'green' : 'gray'};`;
3. Constructing URLs and API endpoints
const userId = 42;
const url = `https://api.example.com/users/${userId}/posts`;
4. Logging and debugging messages
Instead of messy concatenation:
console.log(`User ${username} performed ${action} at ${new Date().toLocaleTimeString()}`);
5. Tagged templates (advanced)
A more advanced feature where you can parse template literals with a function. Libraries like styled-components use this. For now, just know it exists.
Quick reference: traditional strings vs template literals
| Feature | Old way (' ' or " ") | Template literal () |
|---|---|---|
| Variable embedding | "Hello " + name |
`Hello ${name}` |
| Multi-line strings | Requires \n
|
Just press Enter |
| Expressions inside string | Must calculate outside |
${a + b} directly |
| Readability | Gets cluttered with + | Natural and fluid |
| Quotes inside string | Escape with \" or mix quote types |
Can use both ' and " freely |
Conclusion
Template literals may seem like a small syntactic sugar, but they solve genuine pain points that every JavaScript developer faces daily. Once you get comfortable with backticks and ${}, you'll wonder how you ever managed without them.
To recap:
- They eliminate the clutter of
+concatenation. - They let you embed any expression directly inside strings.
- Multi-line strings become natural, no escape sequences needed.
- They drastically improve readability, especially for HTML generation and dynamic messages.
If you're just starting with JavaScript, make template literals your default way of writing strings. It'll make your code clean from day one.
Hope you liked this blog. If thereβs any mistake or something I can improve, do tell me. You can find me on LinkedIn and X, I post more stuff there.
Top comments (0)