JavaScript Template Strings
8 April 2025 | Category: JavaScript
Template Strings (also called Template Literals) are a modern way to create strings in JavaScript. They were introduced in ES6 (ECMAScript 2015) and are more flexible and readable than traditional string syntax.
✅ What is a Template String?
Template strings allow you to:
- Embed variables and expressions directly inside a string
- Use multiline strings easily
- Avoid messy string concatenation
Instead of quotes ('
or "
) we use backticks:
let text = `This is a template string`;
🔹 1. String Interpolation (Insert Variables)
You can embed variables inside ${...}
:
let name = "John";
let age = 25;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // Output: My name is John and I am 25 years old.
🔹 2. Expression Evaluation
You can run simple expressions inside template strings:
let a = 10;
let b = 5;
let result = `The sum is ${a + b}`;
console.log(result); // Output: The sum is 15
🔹 3. Multiline Strings
No need for \n
or string concatenation:
let poem = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you!`;
console.log(poem);
🔹 4. Function Calls Inside Template Strings
You can even call functions:
function greet(name) {
return `Hello, ${name}!`;
}
let message = `${greet("Alice")}`;
console.log(message); // Output: Hello, Alice!
🔹 5. Nested Templates (Advanced)
You can use nested expressions or ternary operators:
let user = "Admin";
let message = `${user === "Admin" ? "Welcome, admin!" : "Welcome, guest!"}`;
console.log(message); // Output: Welcome, admin!
🧠 Summary
Feature | Traditional Strings | Template Strings |
---|---|---|
Use quotes | 'Hello' | `Hello` |
Multiline support | ❌ Use \n | ✅ Multiline natively |
Variable insertion | 'Hello ' + name | `Hello ${name}` |
Expression support | ❌ Not supported | ✅ ${a + b} |
💡 Tip: Use Template Strings in HTML too!
let title = "Dashboard";
document.body.innerHTML = `<h1>${title}</h1>`;