What are JS template literals and how do they work?
- User
What are JS template literals and how do they work?
Assistant
JavaScript template literals are a powerful feature introduced in ES6 (ECMAScript 2015) that enhance string creation and manipulation. Here's a structured overview of their key aspects:
Syntax
- **Backticks (
):** Template literals are enclosed in backticks (), allowing for multi-line strings and embedded expressions.`Hello, World!` // Basic template literal
Key Features
-
String Interpolation
- Embedded Expressions: Use
${expression}to embed variables, calculations, or function calls directly within strings.let name = "Alice"; console.log(`Hello, ${name}`); // "Hello, Alice" let a = 5, b = 10; console.log(`Sum: ${a + b}`); // "Sum: 15" function greet() { return "Hi"; } console.log(`${greet()} there!`); // "Hi there!"
- Embedded Expressions: Use
-
Multi-line Strings
- Preserve line breaks and indentation without needing escape characters (
\n).let poem = `Roses are red, Violets are blue, I'm learning JS, And so can you!`; console.log(poem); // Output: // Roses are red, // Violets are blue, // I'm learning JS, // And so can you!
- Preserve line breaks and indentation without needing escape characters (
-
Embedded Quotes & Escaping
- Use single/double quotes inside without escaping. Escape backticks with
\.let sentence = `He said, "I'm learning JS!"`; // Valid let backtickExample = `This is a backtick: \``; // "This is a backtick: `"
- Use single/double quotes inside without escaping. Escape backticks with
-
Tagged Templates
- A function processes the string and its expressions. The tag function receives an array of string parts and substitution values.
function highlight(strings, ...values) { return strings.flatMap((str, i) => [str, `<mark>${values[i]}</mark>`]).join(''); } let theme = "JavaScript", excitement = "!"; let message = highlight`Learning ${theme} is fun${excitement}`; // "<mark>Learning </mark><mark>JavaScript</mark><mark> is fun</mark><mark>!</mark>"
- A function processes the string and its expressions. The tag function receives an array of string parts and substitution values.
-
Raw Strings
String.rawpreserves escape characters (e.g.,\nas literal text).console.log(String.raw`Line1\nLine2`); // "Line1\nLine2" (not a new line)
Advantages
- Readability: Cleaner syntax for dynamic strings and multi-line content.
- Flexibility: Supports complex logic via tagged templates.
- Safety: Simplifies handling of quotes and special characters.
Use Cases
- Dynamic HTML generation.
- Multi-line user messages or configurations.
- Logging with variable interpolation.
- Custom string processing with tags (e.g., localization, formatting).
Considerations
- Browser Support: Widely supported in modern browsers but not in older environments (e.g., IE11).
- Learning Curve: Tagged templates may require deeper understanding for advanced use.
Example Summary
const user = "Alice"; const items = 5; const price = 10.5; // Interpolation console.log(`User: ${user}, Total: $${items * price}`); // "User: Alice, Total: $52.5" // Multi-line const info = `User: ${user} Items: ${items} Price: $${price}`; /* Output: User: Alice Items: 5 Price: $10.5 */ // Tagged template example function formatCurrency(strings, ...values) { return strings[0] + values.map(v => `$${v.toFixed(2)}`).join(strings.slice(1)); } const total = formatCurrency`Total: ${items * price}`; // "Total: $52.50"Template literals streamline string operations, making JavaScript code more expressive and maintainable.
- **Backticks (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.