JavaScript Template Literals. A Comprehensive Guide
by Pinta
2 min read
Template literals, introduced in ECMAScript 6 (ES6), offer a powerful way to work with strings in JavaScript. They allow for easy interpolation of variables, expressions, and even multiline strings. In this guide, we'll explore the syntax, features, and best practices of template literals through numerous examples.
Basic Usage of Template Literals
const greeting = `Hello, World!`;
console.log(greeting); // Outputs: Hello, World!
Syntax
Template literals are enclosed in backticks (` `), unlike single or double quotes used for traditional strings.
Multiline Strings
Creating multiline strings is simplified with template literals.
const multiline = `This is a
multiline
string.`;
console.log(multiline);
// Outputs:
// This is a
// multiline
// string.
Interpolation and Expressions
Variable Interpolation
You can interpolate variables using ${}
within template literals.
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Outputs: Hello, Alice!
Expression Evaluation
Template literals allow you to evaluate expressions.
const x = 5;
const y = 10;
const result = `The sum of ${x} and ${y} is ${x + y}.`;
console.log(result); // Outputs: The sum of 5 and 10 is 15.
Tagged Template Literals
Tagged template literals involve using a function (a "tag") to process the template literal. This enables advanced string manipulation.
Custom Tag Functions
Create a custom tag function to modify the template literal's behavior.
function currency(strings, ...values) {
const formatted = values.map((value, index) => `${value.toFixed(2)} ${strings[index + 1]}`);
return formatted.join("");
}
const price = 19.99;
const tax = 0.2;
const invoice = currency`Price: ${price} Tax: ${price * tax}`;
console.log(invoice); // Outputs: Price: 19.99 Tax: 4.00
Advanced Features
Raw Strings
The raw
property of template literals allows access to the raw, unprocessed string content.
function rawString(strings, ...values) {
console.log(strings); // Outputs: ["Line 1\nLine 2"]
console.log(values); // Outputs: undefined
console.log(strings.raw); // Outputs: ["Line 1\\nLine 2"]
}
rawString`Line 1\nLine 2`;
String Nesting
Template literals can be nested within each other.
const nested = `Outer: ${`Inner: ${42}`}`;
console.log(nested); // Outputs: Outer: Inner: 42
Use Cases and Best Practices
Generating HTML Templates
Template literals are excellent for generating HTML templates.
const name = "John";
const age = 30;
const html = `
<div>
<h2>${name}</h2>
<p>Age: ${age}</p>
</div>
`;
document.body.innerHTML = html;
Constructing Dynamic SQL Queries
Template literals make it easier to construct dynamic SQL queries.
function createQuery(table, fields) {
return `SELECT ${fields.join(", ")} FROM ${table}`;
}
const tableName = "users";
const selectedFields = ["name", "email"];
const query = createQuery(tableName, selectedFields);
console.log(query); // Outputs: SELECT name, email FROM users
Best Practices: String Escaping
When dealing with user-generated content or external data, ensure proper string escaping to prevent security vulnerabilities.
const userInput = '<script>alert("Hello!")</script>';
const safeHTML = `<p>${userInput}</p>`;
console.log(safeHTML); // Renders user input as text, not executing the script
Conclusion
Template literals are a versatile feature of ES6 that simplify string manipulation and interpolation in JavaScript. By mastering them, you can write cleaner, more readable code for tasks ranging from simple variable substitution to complex string formatting.
Now, go ahead and use template literals to enhance your JavaScript projects and make your code more expressive!