JavaScript Template Literals Explained (Backticks & Strings)
Direct Answer & Key Concept
Template literals are string literals delimited by backticks (`) that allow embedded expressions, string interpolation with ${}, multiline strings, and tagged template functions.
// Template Literals with Expressions
const candidate = {
name: "Alex Mercer",
score: 95,
passingScore: 80
};
const message = `Assessment Results for ${candidate.name}:
- Score: ${candidate.score}%
- Result: ${candidate.score >= candidate.passingScore ? "PASSED" : "FAILED"}`;
console.log(message);What are template literals in JavaScript?
Introduced in ECMAScript 2015 (ES6), template literals are string literals delimited by backtick (`) characters rather than single (') or double (") quotation marks. They provide native support for:
- String interpolation: Embedding dynamic expressions directly inside strings using
${expression}syntax. - Multiline strings: Retaining whitespace and line breaks without concatenation or
\nescape characters. - Tagged template literals: Passing strings through custom parser functions for advanced formatting and sanitization.
Expression Interpolation vs Traditional Concatenation
Prior to template literals, assembling strings with variables required cumbersome plus-sign concatenation:
const user = "Alex";
const unread = 5;
// Old syntax (concatenation)
const oldStr = "Hello " + user + ", you have " + unread + " unread messages.";
// Modern template literal
const newStr = `Hello ${user}, you have ${unread} unread messages.`;
Any valid JavaScript expression can be evaluated inside the ${} delimiters, including ternary operators, mathematical calculations, and function calls:
const item = { name: "Book", price: 20 };
const receipt = `Total: $${item.price > 15 ? item.price * 0.9 : item.price} (with discount)`;
console.log(receipt); // Total: $18 (with discount)
Multiline Strings
Template literals respect natural carriage returns directly within the source code:
const htmlMarkup = `
<div class="card">
<h2>${item.name}</h2>
<p>Price: $${item.price}</p>
</div>
`;
What are Tagged Template Literals?
Tagged templates allow you to parse template literals with a custom function. The tag function receives raw string segments as an array along with evaluated interpolation values:
function highlight(strings, ...values) {
return strings.reduce((acc, str, i) => {
return `${acc}${str}${values[i] ? `<strong>${values[i]}</strong>` : ""}`;
}, "");
}
const product = "Compiler";
console.log(highlight`Welcome to JS CodeLab ${product}!`);
// "Welcome to JS CodeLab <strong>Compiler</strong>!"
Libraries like styled-components and SQL query builders utilize tagged templates to sanitize inputs and construct domain-specific languages.