Template literals, introduced in ES6, offer a cleaner and more readable way to concatenate strings compared to traditional string concatenation methods. They are enclosed by backticks ( `` ) instead of single or double quotes.
Simple String Concatenation:
// Traditional approach: const name = "John"; const age = 30; const greeting = "Hello, my name is " + name + " and I am " + age + " years old."; // Template literal approach: const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
Explanation:
- Template literals are enclosed in backticks (``).
- Expressions are embedded within dollar signs and curly braces (${expression}).
- The value of the expression is directly inserted into the string.
Multi-line Strings:
// Traditional approach: const message = "This is a\nlong message\nspread across\nmultiple lines."; // Template literal approach: const message = `This is a long message spread across multiple lines.`;
Explanation:
- Line breaks within template literals are preserved, making multi-line strings easier to read.
String Interpolation with Variables and Functions:
// Traditional approach: const temperature = 25; const message = "The current temperature is " + temperature + "°C."; // Template literal approach: const message = `The current temperature is ${temperature}°C.`; // With function call: const formattedTemperature = formatTemperature(temperature); const message = `The current temperature is ${formattedTemperature}.`;
Explanation:
- Any expression, including variables and function calls, can be used within template literals.
String Interpolation with Conditional Statements:
// Traditional approach: const isWeekend = true; const message = (isWeekend ? "It's the weekend!" : "It's a weekday."); // Template literal approach: const message = `Today is ${isWeekend ? "the weekend" : "a weekday"}.`;
Explanation:
- Template literals allow embedding conditional statements for dynamic string construction.
Tagged Templates for Advanced Formatting:
This function takes the raw strings and interpolated values from the template literal and uses them to create a formatted string with highlighted values.
function highlightString(strings, ...values) { let result = ''; for (let i = 0; i < strings.length; i++) { result += strings[i]; if (i < values.length) { result += `<span style="color: red;">${values[i]}</span>`; } } return result; } const name = "Sachin"; const age = 30; const highlightedMessage = highlightString`Hello, ${name}! You are ${age} years old.`; console.log(highlightedMessage); // Output: "<span style="color: red;">Hello, Sachin!</span> You are <span style="color: red;">30</span> years old."