Problem Statement
What are template literals and what are their advantages over regular strings? Explain with examples.
Explanation
Template literals are string literals using backticks that provide enhanced string functionality introduced in ES6.
Key features:
String interpolation allows embedding expressions using dollar sign and curly braces. Any JavaScript expression can be embedded including variables, calculations, and function calls.
Multi-line strings work naturally without escape characters. Just press enter to create new lines. This makes code much more readable.
Expression evaluation happens automatically. The result is converted to a string and inserted.
Advantages over regular strings:
Cleaner syntax for string concatenation. No need for plus operators.
Easier to read, especially with variables.
Natural multi-line support without backslash n.
Can embed any expression, not just variables.
Better for creating HTML templates.
Tagged templates for advanced use cases:
You can create custom string processing by tagging template literals with a function. The function receives string parts and values separately. Useful for internationalization, styling, or sanitization.
Common use cases:
Building dynamic messages.
Creating HTML markup.
SQL queries with parameters.
Formatting output.
Logging with context.
Template literals are one of the most useful ES6 features and are used extensively in modern JavaScript and frameworks like React.
Code Solution
SolutionRead Only
const name = 'John';
const age = 30;
const city = 'New York';
// STRING INTERPOLATION
// Old way
const oldWay = 'My name is ' + name + ', I am ' + age + ' years old';
// Template literal way (cleaner)
const newWay = `My name is ${name}, I am ${age} years old`;
console.log(newWay);
// EXPRESSIONS
// Any expression works
console.log(`Double age: ${age * 2}`);
console.log(`Next year: ${age + 1}`);
console.log(`Name length: ${name.length}`);
// Function calls
function getGreeting() {
return 'Hello';
}
console.log(`${getGreeting()}, ${name}!`);
// Ternary operators
const status = `User is ${age >= 18 ? 'adult' : 'minor'}`;
console.log(status);
// MULTI-LINE STRINGS
// Old way (messy)
const oldMultiLine = 'Line 1\n' +
'Line 2\n' +
'Line 3';
// Template literal way (natural)
const newMultiLine = `
Line 1
Line 2
Line 3
`;
// HTML TEMPLATES
const user = {
name: 'Jane',
email: 'jane@example.com',
role: 'Admin'
};
const userCard = `
<div class="user-card">
<h2>${user.name}</h2>
<p>Email: ${user.email}</p>
<span class="badge">${user.role}</span>
</div>
`;
// Dynamic lists
const items = ['Apple', 'Banana', 'Orange'];
const list = `
<ul>
${items.map(item => `<li>${item}</li>`).join('')}
</ul>
`;
// TAGGED TEMPLATES (advanced)
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] ? `<mark>${values[i]}</mark>` : '');
}, '');
}
const highlighted = highlight`Hello ${name}, you are ${age} years old`;
console.log(highlighted);
// 'Hello <mark>John</mark>, you are <mark>30</mark> years old'
// PRACTICAL EXAMPLES
// API URL building
const userId = 123;
const apiUrl = `https://api.example.com/users/${userId}/posts`;
// SQL queries (be careful with injection!)
const query = `
SELECT * FROM users
WHERE name = '${name}'
AND age > ${age}
`;
// Logging with context
console.log(`[${new Date().toISOString()}] User ${name} logged in`);
// Nested templates
const data = {
users: [{name: 'John', age: 30}, {name: 'Jane', age: 25}]
};
const table = `
<table>
${data.users.map(user => `
<tr>
<td>${user.name}</td>
<td>${user.age}</td>
</tr>
`).join('')}
</table>
`;