Template literals, also known as template strings, are a way to include dynamic expressions in strings in JavaScript. They were introduced in ECMAScript 6 (ES6) and provide a more concise and readable syntax than traditional string concatenation.
Template literals are enclosed in backticks ( ) instead of single quotes or double quotes. Inside the backticks, you can include placeholders ($expression) for dynamic values, which are evaluated and replaced with their values at runtime.
Hereβs an example of how to use template literals:
const name = "John";
const age = 30;
const message = `My name is ${name}, and I am ${age} years old.`;
console.log(message);
// Outputs "My name is John, and I am 30 years old."
In this example, the message variable contains a template literal that includes placeholders for the name and age variables. When the template literal is evaluated, the placeholders are replaced with their values to create a dynamic string.
Template literals can also be used for multi-line strings and to include special characters like newlines, tabs, and quotes:
const message = `This is a
multi-line
string.
It also includes "quotes" and special characters like t and n.`;
console.log(message);
/*
Outputs:
This is a
multi-line
string.
It also includes "quotes" and special characters like t and n.
*/
Template literals can improve the readability and maintainability of code by making it easier to include dynamic values and format strings. They are also often used with tagged template literals to create more powerful and flexible string manipulation functions.