JavaScript template literals provide a convenient way to create strings that include variables or expressions. They use backticks (`) instead of single or double quotes, and allow for the interpolation of variables or expressions using ${} notation.
Eexample
const name = "John";
const age = 25;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
In this example, a template literal is used to create a string that includes the values of the name
and age
variables. The ${}
notation is used to insert the values of these variables into the string.
Template literals can also be used for multiline strings. Instead of using the escape character (\
) to insert line breaks, you can simply use the Enter key to add line breaks within the template literal.
const message = `Hello,
my name is John,
and I am 25 years old.`;
Template literals can also be used with tagged templates, which allow you to process the template literal with a function.
Example
function tag(strings, ...values) {
console.log(strings); // ["Hello, my name is ", " and I am ", "."]
console.log(values); // ["John", 25]
return `Processed string`;
}
const name = "John";
const age = 25;
const message = tag`Hello, my name is ${name} and I am ${age} years old.`;
In this example, the tag
function is used to process the template literal. The strings
parameter is an array of the string segments of the template literal, and the values
parameter is an array of the interpolated values. The function can then process these values and return a processed string.
Highlights
Template literals provide a convenient and powerful way to create strings in JavaScript. By understanding how to use template literals, you can create more flexible and readable code that includes variables, expressions, and even multiline strings.