String templates, also known as template literals, are a feature in JavaScript that allows you to create multi-line strings and embed expressions in a cleaner and more readable way. Template literals use backticks (`) instead of single or double quotes.
1. Syntax of Template Literals
let message = `Hello, World!`; console.log(message); // Output: Hello, World!
Key Features:
- Enclosed by backticks (
`) instead of single (') or double (") quotes. - Can contain placeholders indicated by
${expression}for embedding expressions.
2. Multi-line Strings
With template literals, you can create multi-line strings without using newline characters (\n).
let multiLineString = `This is a multi-line string.`; console.log(multiLineString);
Output:
Output: This is a multi-line string.
3. String Interpolation
Template literals allow you to embed expressions within the string using ${} syntax.
let name = 'John';
let age = 30;
let greeting = `My name is ${name} and I am ${age} years old.`;
console.log(greeting); // Output: My name is John and I am 30 years old.
Key Points:
- Expressions can be variables, function calls, or any valid JavaScript expressions.
4. Expressions in Template Literals
You can perform operations or call functions inside the template literal expressions.
let a = 10;
let b = 20;
let sum = `The sum of a and b is ${a + b}.`;
console.log(sum); // Output: The sum of a and b is 30.
5. Tagged Templates
A tagged template allows you to modify the output of a template literal using a custom function.
function tag(strings, ...values) {
console.log(strings); // Array of string literals
console.log(values); // Array of values
return 'Custom Output';
}
let result = tag`Hello, ${name}! You are ${age} years old.`;
console.log(result); // Output: Custom Output
Key Points:
- The tag function takes the string literals and the values as arguments.
- It can manipulate or transform the output.
6. Using Template Literals in Functions
Template literals can be very useful for creating dynamic messages in functions.
function greet(name) {
return `Hello, ${name}! Welcome to our website.`;
}
console.log(greet('Alice')); // Output: Hello, Alice! Welcome to our website.
Summary
- Multi-line Strings: Easily create strings spanning multiple lines.
- String Interpolation: Embed variables and expressions directly in the string.
- Tagged Templates: Use custom functions to manipulate the output of template literals.
Template literals provide a more readable and flexible way to work with strings in JavaScript, making it easier to handle dynamic content and multi-line strings efficiently.