What are Template Literals?
Template literals (also called template strings) were introduced in ES6 and offer a powerful, modern syntax for working with strings in JavaScript. They are enclosed in backticks (``) instead of single or double quotes. Unlike older string types, template literals provide:
- String interpolation — inject variables or expressions directly into your string using
${expression}, so you don’t need to concatenate with `+`.— Allows embedding results like${a + b}or function calls. - Multiline strings — preserve line breaks and whitespace exactly as typed across multiple lines inside backticks, without using `\n` or string concatenation.— Newlines in template literals become actual line breaks in the resulting string.
- Tagged templates — prefix a template literal with a function to customize how it's processed. The tag function receives literal segments and embedded values for advanced formatting, escaping, or localization.— Enables safe HTML output, localization, or custom string processing.
Example:
// Defining a variable
const name = "Prakash";
// Using template literal to create a greeting message
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Prakash!Nested Template Literals
Example :
let color = "red";
let count = 3;
let message = `I have ${color ? `${count} ${color}` : count} apples`;
console.log(message); // Output: "I have 3 red apples"
Note :This structure can sometimes reduce readability, especially when you have complex logic or nested expressions. It's a valid, but confusing, not recommended.
Embedding Expressions
Template literals allow you to embed expressions directly into the string using the ${} syntax.
Example:
// Defining variables
const a = 5;
const b = 10;
// Embedding expressions in a template literal
console.log(`The sum of a and b is ${a + b}`); // Output: The sum of a and b is 15Multiline Strings
Before ES6, creating multiline strings required concatenation or escaping newlines. Template literals make this process much simpler.
Example:
// Creating a multiline string with template literals
const multiline = `This is a multiline string.
It spans multiple lines without any issues.`;
console.log(multiline);Tagged Template Literals
Tagged template literals are an advanced form of template literals in JavaScript. Instead of returning a simple string, they allow you to pass a template literal to a function (called a "tag function") that can customize the output.
The tag function receives the literal string segments as the first argument (an array), and the values of the expressions as the remaining arguments. This is especially useful for escaping HTML, translating strings, formatting output, or even building custom DSLs (domain-specific languages).
Syntax: tagFunction`template ${expr1} ... ${exprN}`
Example:
// A tag function to wrap expressions in <strong> tags
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
// Append each string part and wrap expressions in <strong> tags
return result + str + (values[i] ? `<strong>${values[i]}</strong>` : "");
}, "");
}
// Sample values
const name = "Prakash";
const age = 25;
// Use the tag function with a template literal
const result = highlight`My name is ${name} and I am ${age} years old.`;
console.log(result);
// Output: My name is <strong>Prakash</strong> and I am <strong>25</strong> years old.
In this example, the highlight function intercepts the template literal and modifies the output, wrapping each interpolated expression in a <strong> tag. This demonstrates how tagged templates can help customize the rendering of dynamic data.
Using Template Literals with Functions
Template literals work seamlessly with functions, allowing dynamic strings to be passed as arguments.
Example:
// Function that generates a dynamic message
function createMessage(user, action) {
return ${user} has ${action} the document.`;
}
// Calling the function with template literal arguments
const message = createMessage("Prakash", "approved");
console.log(message); // Output: Prakash has approved the document.Benefits of Template Literals
- Cleaner and more readable syntax.
- Easy embedding of variables and expressions.
- Simplifies creating multiline strings.
- Enhances flexibility with tagged templates.