Template Literals & Modern Strings
Template literals use backticks (`) instead of quotes. They make strings with variables, HTML snippets, and multi-line text readable — essential for UI work in React and email templates in Node.
Basic interpolation
const name = 'Sandeep';
const course = 'ES6 Basics';
// Old
const msg1 = 'Hi ' + name + ', welcome to ' + course;
// ES6 — template literal
const msg2 = `Hi ${name}, welcome to ${course}`;
Multi-line strings
const emailHtml = `
<h1>Your certificate is ready</h1>
<p>Hi ${student.name},</p>
<p>You completed ${courseTitle}.</p>
`;
🌍 Real-world example — Dynamic quiz result message
function resultMessage({ name, score, total }) {
const pct = Math.round((score / total) * 100);
const badge = pct >= 80 ? '🏆' : '📚';
return `${badge} ${name}: you scored ${score}/${total} (${pct}%).`;
}
resultMessage({ name: 'Priya', score: 18, total: 20 });
// "🏆 Priya: you scored 18/20 (90%)."Useful string methods (ES6+)
'hello world'.includes('world'); // true
' trim me '.trim(); // 'trim me'
'file.pdf'.endsWith('.pdf'); // true
'user@email.com'.startsWith('user'); // true
💡 Tip: Use template literals for any string with 2+ variables — your code reviews will thank you.
⚠️ Common Mistake: Forgetting backticks and using single quotes with ${name} — that prints literal "${name}", not the variable.
👨🏫 Teaching note: Exercise: build an invoice string with 4 interpolated fields (customer, item, qty, total).