JavaScript template literals (also called template strings) provide a powerful, flexible way to create strings. Introduced in ES6 (ECMAScript 2015), template literals make string formatting easier by supporting interpolation, multiline strings, and embedded expressions.
This tutorial covers everything you need to know about using JavaScript string templates effectively.
1. What Are Template Literals?
Template literals are enclosed by backticks (`
), not single ('
) or double ("
) quotes.
javascriptCopyEditlet name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Alice!"
Unlike traditional strings, template literals support:
- String interpolation using
${}
- Multiline strings without
\n
- Embedded expressions and function calls
2. Basic Syntax
javascriptCopyEdit`string text ${expression} string text`
Example:
javascriptCopyEditlet age = 25;
let intro = `I am ${age} years old.`;
console.log(intro); // "I am 25 years old."
You can embed variables, arithmetic, and even function results inside the ${}
.
3. Multiline Strings
Before ES6, you had to use \n
to write multiline strings:
javascriptCopyEditlet oldWay = "Line one\nLine two";
With template literals:
javascriptCopyEditlet multiline = `Line one
Line two`;
console.log(multiline);
This keeps your code cleaner and more readable.
4. String Interpolation with Variables
Template literals make it easy to insert multiple variables:
javascriptCopyEditlet firstName = "John";
let lastName = "Doe";
let fullName = `My name is ${firstName} ${lastName}.`;
console.log(fullName); // "My name is John Doe."
5. Embedding Expressions
You can insert expressions, not just variables:
javascriptCopyEditlet x = 10;
let y = 5;
let result = `The sum is ${x + y}.`;
console.log(result); // "The sum is 15."
Even function calls can be embedded:
javascriptCopyEditfunction greet(name) {
return `Hi, ${name}`;
}
let message = `${greet("Sam")}, welcome!`;
console.log(message); // "Hi, Sam, welcome!"
6. Nesting Template Literals
You can nest template literals inside each other:
javascriptCopyEditlet user = {
name: "Eva",
age: 22
};
let profile = `Name: ${user.name}, Age: ${user.age > 18 ? "Adult" : "Minor"}`;
console.log(profile); // "Name: Eva, Age: Adult"
7. HTML Templates with Backticks
Template literals are great for building HTML snippets:
javascriptCopyEditlet title = "Welcome";
let content = `<div>
<h1>${title}</h1>
<p>This is a sample HTML template.</p>
</div>`;
document.body.innerHTML = content;
This is helpful for creating dynamic interfaces or rendering templates in vanilla JavaScript.
8. Tagged Templates (Advanced)
A tagged template allows you to customize how a template literal is processed using a function.
Example:
javascriptCopyEditfunction upper(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] ? values[i].toUpperCase() : '');
}, '');
}
let name = "jane";
let message = upper`Hello, ${name}!`;
console.log(message); // "Hello, JANE!"
This is useful for sanitizing inputs, formatting, or building custom DSLs (Domain Specific Languages).
9. Use Cases of Template Literals
- Creating dynamic strings
- Embedding variables and expressions into text
- Generating dynamic HTML in JavaScript
- Simplifying string concatenation
- Making multiline strings easier to read
- Building template systems for front-end frameworks
10. Traditional Concatenation vs Template Literals
Feature | Traditional | Template Literals |
---|---|---|
Syntax | 'Hello ' + name | `Hello ${name}` |
Multiline Support | 'Line 1\nLine 2' | `Line 1\nLine 2` |
Expressions | 'Total: ' + (a + b) | `Total: ${a + b}` |
Readability | Less readable | More readable |
Conclusion
JavaScript string templates (template literals) bring major improvements over older string-handling methods. They are:
✅ Easier to read
✅ More powerful for dynamic content
✅ Ideal for building HTML and formatted text
✅ Supported in all modern browsers
Here’s what you should remember:
- Use backticks (
`
) instead of quotes. - Insert variables or expressions using
${}
. - Take advantage of multiline support and HTML formatting.
- Use tagged templates for advanced customization.