Template Literals
JavaScript template literals, commonly known as backticks (`, grave accent), offer a versatile way to manipulate strings. This article covers practical uses such as creating multiline strings, embedding variables and expressions, and generating dynamic URLs—all illustrated with clear examples. You will learn how to effectively apply template literals to enhance your JavaScript coding.
How to Use Template Literals
Template literals are a new string syntax introduced in JavaScript ES6 (ES2015).
They are designed to make writing and handling strings more convenient.
Unlike traditional string syntax using single (') or double quotes ("), template literals use backticks (`) to enclose strings. Unlike regular strings, template literals allow you to write strings across multiple lines and embed variables and expressions, making string manipulation easier and more intuitive.
The main features of template literals include:
- Multi-line Strings
- Expression Interpolation
Multi-line Strings
With template literals, you can write strings spanning multiple lines without needing extra newline characters or escape sequences.
const multilineString = "First line\n" +
"Second line\n" +
"Third line";
console.log(multilineString);
// Output:
// "First line"
// "Second line"
// "Third line"
In the code above, backslashes and newline characters (\n
) are used to join lines. This method requires additional handling to write multiline strings, which can be inconvenient.
On the other hand, with template literals, you can create multiline strings easily by using backticks (`). Here's an example:
const multilineString = `First line
Second line
Third line`;
console.log(multilineString);
// Output:
// "First line"
// "Second line"
// "Third line"
Using template literals eliminates the need for extra newline characters or escape sequences, improving readability and making your code easier to write.
Template literals provide a convenient way to write multiline strings, simplifying string handling compared to traditional JavaScript methods.
Expression Interpolation
Template literals allow you to embed expressions. To do this, use the $
symbol followed by the expression wrapped in curly braces {}
. For example, the following code inserts the value of the variable name
into a template literal.
Expressions you can embed in template literals include:
- Variables
- Operators
- Function calls
- Object properties
- Array elements
Embedding Variables in Expressions
let name = "John Doe";
const message = "Welcome, " + name + "!";
console.log(message);
// Output: "Welcome, John Doe!"
${expression}
syntax:
let name = "John Doe";
const message = `Welcome, ${name}!`;
console.log(message);
// Output: "Welcome, John Doe!"
Embedding Operators in Expressions
const x = 10;
const y = 5;
const result = `${x} + ${y} = ${x + y}`;
console.log(result);
// Output: 10 + 5 = 15
Embedding Function Calls in Expressions
function greet(name) {
return `Hello, ${name}!`;
}
const userName = "John";
const message = `Greeting message: ${greet(userName)}`;
console.log(message);
// Output: "Greeting message: Hello, John!"
Embedding Object Properties in Expressions
const person = {
name: "John",
age: 30,
greet() {
return `Hello, I am ${this.name}, and I am ${this.age} years old.`;
}
};
const greeting = person.greet();
console.log(greeting);
// Output: "Hello, I am John, and I am 30 years old."
Embedding Array Elements in Expressions
const fruits = ["Apple", "Banana", "Orange"];
const message = `My favorite fruits are ${fruits[0]}, ${fruits[1]}, and ${fruits[2]}.`;
console.log(message);
// Output: "My favorite fruits are Apple, Banana, and Orange."
Template literals’ ability to embed expressions is a powerful feature that makes JavaScript code more concise and easier to read.
Working with Practical Template Literal Examples
This section covers several practical examples demonstrating how to use JavaScript template literals effectively.
- Dynamic URL Generation Example
- HTML Template Creation Example
- HTML Log Message Formatting Example
Dynamic URL Generation Example
const baseURL = "https://api.example.com";
// 1. Basic usage of template literals for URLs
const endpoint1 = `${baseURL}/users`;
console.log(endpoint1); // Output: "https://api.example.com/users"
// 2. Inserting variables into URLs
const userId = 123;
const endpoint2 = `${baseURL}/users/${userId}`;
console.log(endpoint2); // Output: "https://api.example.com/users/123"
// 3. Handling URL parameters
const postId = 456;
const endpoint3 = `${baseURL}/users/${userId}/posts/${postId}`;
console.log(endpoint3); // Output: "https://api.example.com/users/123/posts/456"
// 4. Generating query strings
const params = {
category: "books",
limit: 10,
sort: "desc"
};
const queryString = Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join("&");
const endpoint4 = `${baseURL}/search?${queryString}`;
console.log(endpoint4); // Output: "https://api.example.com/search?category=books&limit=10&sort=desc"
The examples above demonstrate various ways to create dynamic URLs using template literals, from basic URL construction to inserting variables, managing parameters, and generating query strings.
In real projects, values like baseURL
, variables, parameters, and query strings should be adjusted to fit the specific API or context. Use these examples to understand and apply the concepts of dynamic URL creation.
HTML Template Creation Example
// 1. Basic HTML template literal usage
const title = "Welcome!";
const content = "Hello, world!";
const htmlTemplate1 = `
<div class="container">
<h1>${title}</h1>
<p>${content}</p>
</div>
`;
console.log(htmlTemplate1);
// 2. Inserting dynamic data
const user = {
name: "John",
age: 30,
email: "john@example.com"
};
const htmlTemplate2 = `
<div class="user-profile">
<h2>${user.name}</h2>
<p>Age: ${user.age}</p>
<p>Email: ${user.email}</p>
</div>
`;
console.log(htmlTemplate2);
// 3. Creating lists with loops
const todos = [
{id: 1, title: "Buy groceries"},
{id: 2, title: "Do laundry"},
{id: 3, title: "Clean the house"}
];
const todoList = `
<ul>
${todos.map(todo => `<li>${todo.title}</li>`).join("")}
</ul>
`;
console.log(todoList);
// 4. Generating dynamic HTML with conditionals
const isAuthenticated = true;
const loginMessage = `
${isAuthenticated ? `<p>Welcome back, ${user.name}!</p>` : `<p>Please log in.</p>`}
`;
console.log(loginMessage);
These examples show how to create HTML templates using template literals, covering basic usage, dynamic data insertion, list generation with loops, and conditional rendering.
Adjust variables, data, and loop targets as needed in your projects. These examples help you grasp how to build flexible HTML templates using JavaScript.
HTML Log Message Formatting Example
// 1. Basic log message using template literals
const message1 = "Something happened";
console.log(`[INFO] ${message1}`);
// 2. Adding log level and timestamp
function formatLog(level, message) {
const timestamp = new Date().toLocaleString();
return `[${level}] ${timestamp} - ${message}`;
}
const message2 = "An error occurred";
console.log(formatLog("ERROR", message2));
// 3. Inserting dynamic data into logs
function formatLog(level, message, data) {
const timestamp = new Date().toLocaleString();
return `[${level}] ${timestamp} - ${message} - ${JSON.stringify(data)}`;
}
const user = {id: 123, name: "John"};
console.log(formatLog("DEBUG", "User logged in", user));
This section covers different ways to format log messages using template literals, including basic messages, adding log levels and timestamps, and inserting dynamic data.
In practice, customize log messages, levels, and timestamps according to your project needs. Use these examples to understand how to format logs clearly and efficiently.
Specifications
Specification | |
---|---|
Template literals |
ECMAScript Language Specification #sec-template-literals |
Browser compatibility
Syntax |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
Template literals
|
41 | 12 | 34 | 9 |