Template literals are a feature introduced in ES6 (ECMAScript 2015) that provide a more powerful and flexible way to work with strings. They allow for string interpolation, multiline strings, and the inclusion of expressions within a string.
String Interpolation:
Template literals allow embedding expressions directly within strings using ${}
.
Syntax:
let name = 'Alice';
let greeting = `Hello, ${name}!`; // String interpolation
console.log(greeting); // Output: "Hello, Alice!"
Multiline Strings:
With template literals, you can create strings that span multiple lines without using escape characters like \\\\n
.
Syntax:
let message = `This is a message
that spans multiple
lines.`;
console.log(message);
// Output:
// This is a message
// that spans multiple
// lines.
Embedding Expressions:
You can embed any valid JavaScript expression (e.g., variables, operations, function calls) inside ${}
within a template literal.
Syntax:
let a = 5;
let b = 10;
let result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // Output: "The sum of 5 and 10 is 15."
Tagged Template Literals:
A more advanced feature where you can define custom processing for a template literal by using a tag function.
Syntax:
function tag(strings, ...values) {
console.log(strings); // Array of string literals
console.log(values); // Array of interpolated values
}
let name = 'Alice';
let age = 30;
tag`Hello, my name is ${name} and I am ${age} years old.`;
// Output:
// [ 'Hello, my name is ', ' and I am ', ' years old.' ]
// [ 'Alice', 30 ]
let firstName = 'John';
let lastName = 'Doe';
let age = 25;
let message = `Hello, my name is ${firstName} ${lastName} and I am ${age} years old.`;
console.log(message); // Output: "Hello, my name is John Doe and I am 25 years old."
// Multiline string
let address = `123 Main St
City, Country
Postal Code`;
console.log(address);
// Using expressions in template literals
let price = 100;
let discount = 20;
let finalPrice = `The final price after ${discount}% discount is $${price - (price * discount / 100)}.`;
console.log(finalPrice); // Output: "The final price after 20% discount is $80."
\\\\n
for newlines or \\\\"
for quotes in strings.In summary, template literals offer a more readable and efficient way to handle strings in JavaScript, especially when working with dynamic data and multiline content.