JavaScript String Templates
String templates, also known as template literals, allow for easier string interpolation and multi-line strings. They are enclosed by backticks (`) rather than single or double quotes.
1. Basic Syntax
Template literals are enclosed in backticks and can contain placeholders for variables and expressions. Placeholders are indicated by the dollar sign and curly braces (${expression}
).
const name = 'Alice';
const age = 25;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting); // 'Hello, my name is Alice and I am 25 years old.'
2. Multi-line Strings
Template literals support multi-line strings without the need for escape sequences.
const message = `This is a message
that spans multiple
lines.`;
console.log(message);
// 'This is a message
// that spans multiple
// lines.'
3. Expression Interpolation
You can include any valid JavaScript expression inside the placeholder. The expression will be evaluated, and the result will be inserted into the string.
const a = 5;
const b = 10;
const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // 'The sum of 5 and 10 is 15.'
4. Tagged Templates
Tagged templates allow you to parse template literals with a custom function. The function receives the template literal's parts and placeholders as arguments.
function tag(strings, ...values) {
return strings.reduce((acc, str, i) => acc + str + (values[i] || ''), '');
}
const name = 'Bob';
const age = 30;
const message = tag`Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // 'Hello, my name is Bob and I am 30 years old.'