Template strings, also known as template literals, provide an elegant way to create strings in JavaScript, allowing for easy interpolation of variables and expressions within the string. They are enclosed by backticks (`\`) instead of single or double quotes.
Examples of using template strings in JavaScript:
1. Basic usage:
let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!
2. Multiline strings:
let multiline = ` This is a multiline string.`; console.log(multiline); /* Output: This is a multiline string. */
3. Expression interpolation:
let a = 10;
let b = 20;
let result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // Output: The sum of 10 and 20 is 30.
4. Function interpolation:
function capitalize(str) {
return str.toUpperCase();
}
let message = `The word "hello" in uppercase is ${capitalize('hello')}.`;
console.log(message); // Output: The word "hello" in uppercase is HELLO.
5. Tagged template literals:
function tag(strings, ...values) {
console.log(strings); // Output: ["The result is ", "."]
console.log(values); // Output: [10 * 20]
return strings[0] + (values[0] * values[1]) + strings[1];
}
let a = 10, b = 20;
let result = tag`The result is ${a * b}.`;
console.log(result); // Output: The result is 200.
Template strings provide a more concise and readable syntax compared to traditional string concatenation, especially when dealing with dynamic content or multiline strings. They are widely used in modern JavaScript development.
Code Compiler Link: https://app.singhteekam.in/codecompiler/