Template Literals
Template Literals
Section titled “Template Literals”What it is
Section titled “What it is”Template literals (template strings) allow embedded expressions and multi-line strings using backticks. Introduced in ES6 (2015), they provide a cleaner way to create strings with dynamic content.
Before this feature
Section titled “Before this feature”String concatenation was verbose and error-prone:
// Concatenationconst name = "Alice";const age = 25;const message = "Hello, " + name + "! You are " + age + " years old.";
// Multi-line strings required escapingconst html = "<div>\n" + " <h1>Title</h1>\n" + " <p>Content</p>\n" + "</div>";
// Complex expressionsconst price = 19.99;const quantity = 3;const total = "Total: $" + (price * quantity).toFixed(2);After this feature
Section titled “After this feature”Template literals provide clean, readable syntax:
// String interpolationconst name = "Alice";const age = 25;const message = `Hello, ${name}! You are ${age} years old.`;
// Multi-line stringsconst html = ` <div> <h1>Title</h1> <p>Content</p> </div>`;
// Expressionsconst price = 19.99;const quantity = 3;const total = `Total: $${(price * quantity).toFixed(2)}`;
// Nested templatesconst user = { name: "Bob", premium: true };const badge = `${user.name} ${user.premium ? `⭐` : ``}`;
// Function callsconst formatted = `Date: ${new Date().toLocaleDateString()}`;
// Tagged templates (advanced)function highlight(strings, ...values) { return strings.reduce((result, str, i) => { return `${result}${str}<mark>${values[i] || ''}</mark>`; }, '');}const term = "JavaScript";const text = highlight`Learn ${term} today!`;// "Learn <mark>JavaScript</mark> today!"Why this is better
Section titled “Why this is better”- Readable: No more
+concatenation - Multi-line: Natural multi-line strings without
\n - Expressions: Any JavaScript expression inside
${} - Maintainable: Less error-prone than string concatenation
- Powerful: Tagged templates enable custom string processing
Key notes / edge cases
Section titled “Key notes / edge cases”- Use backticks (`), not quotes
- Whitespace is preserved (including leading/trailing)
- Can nest template literals
- Expressions are coerced to strings
- Tagged templates receive strings and values separately
- Escape backtick with ```
// Whitespace preservedconst text = ` Line 1 Line 2`;// Includes leading newline and spaces
// Trim if neededconst trimmed = ` Line 1 Line 2`.trim();
// Expressions coerced to stringconst count = 5;const msg = `Count: ${count}`; // "Count: 5"const obj = { x: 1 };const msg2 = `Object: ${obj}`; // "Object: [object Object]"
// Escape backtickconst code = `Use \`backticks\` for templates`;
// Conditional contentconst user = { name: "Alice", isAdmin: true };const greeting = ` Welcome, ${user.name}! ${user.isAdmin ? 'You have admin access.' : ''}`;Quick practice
Section titled “Quick practice”-
Create a string “Product: Laptop, Price: $999” using template literal
Answer
const product = "Laptop";const price = 999;const message = `Product: ${product}, Price: $${price}`; -
Convert:
"Hello, " + name + "! Welcome to " + site + "."Answer
`Hello, ${name}! Welcome to ${site}.` -
Create a multi-line HTML string for a card component
Answer
const title = "Article Title";const content = "Article content...";const card = `<div class="card"><h2>${title}</h2><p>${content}</p></div>`;