javascript
examples
examples.js⚡javascript
// ============================================
// 17.2 Template Literals - Examples
// ============================================
// --------------------------------------------
// 1. Basic String Interpolation
// --------------------------------------------
const name = 'Alice';
const age = 30;
// Traditional concatenation
const greeting1 = 'Hello, ' + name + '! You are ' + age + ' years old.';
// Template literal
const greeting2 = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting1);
console.log(greeting2);
// Both: 'Hello, Alice! You are 30 years old.'
// --------------------------------------------
// 2. Expression Interpolation
// --------------------------------------------
const a = 10;
const b = 5;
console.log(`Sum: ${a + b}`); // Sum: 15
console.log(`Product: ${a * b}`); // Product: 50
console.log(`A > B? ${a > b}`); // A > B? true
console.log(`Max: ${Math.max(a, b)}`); // Max: 10
// Ternary expressions
const score = 85;
console.log(`Grade: ${score >= 90 ? 'A' : score >= 80 ? 'B' : 'C'}`);
// Grade: B
// Method calls
const text = 'hello world';
console.log(`Uppercase: ${text.toUpperCase()}`);
// Uppercase: HELLO WORLD
// --------------------------------------------
// 3. Multi-line Strings
// --------------------------------------------
// Traditional (escaped newlines)
const multiTraditional = 'Line 1\n' + 'Line 2\n' + 'Line 3';
// Template literal (natural newlines)
const multiTemplate = `Line 1
Line 2
Line 3`;
console.log(multiTraditional);
console.log(multiTemplate);
// HTML template
const user = { name: 'Alice', role: 'Admin' };
const html = `
<div class="user-card">
<h2>${user.name}</h2>
<p>Role: ${user.role}</p>
</div>
`;
console.log(html);
// --------------------------------------------
// 4. Preserving Whitespace
// --------------------------------------------
const indented = `
This text
preserves indentation
exactly as written
`;
console.log(indented);
// Trim if needed
const trimmed = `
Content here
`.trim();
console.log(trimmed); // 'Content here'
// --------------------------------------------
// 5. Nesting Template Literals
// --------------------------------------------
const items = ['Apple', 'Banana', 'Cherry'];
const list = `
<ul>
${items.map((item) => ` <li>${item}</li>`).join('\n')}
</ul>
`;
console.log(list);
// Conditional nesting
const isLoggedIn = true;
const username = 'Alice';
const navbar = `
<nav>
${
isLoggedIn
? `<span>Welcome, ${username}</span>
<button>Logout</button>`
: `<button>Login</button>`
}
</nav>
`;
console.log(navbar);
// --------------------------------------------
// 6. Tagged Template Basics
// --------------------------------------------
function simpleTag(strings, ...values) {
console.log('Strings:', strings);
console.log('Values:', values);
// Reconstruct the string
return strings.reduce((result, str, i) => {
return result + str + (values[i] !== undefined ? values[i] : '');
}, '');
}
const tagResult = simpleTag`Hello, ${name}! You are ${age} years old.`;
console.log('Result:', tagResult);
// Strings: ['Hello, ', '! You are ', ' years old.']
// Values: ['Alice', 30]
// Result: 'Hello, Alice! You are 30 years old.'
// --------------------------------------------
// 7. HTML Escape Tag
// --------------------------------------------
function escapeHTML(strings, ...values) {
const escape = (str) =>
String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
return strings.reduce((result, str, i) => {
const value = values[i] !== undefined ? escape(values[i]) : '';
return result + str + value;
}, '');
}
const userInput = '<script>alert("XSS")</script>';
const safeHTML = escapeHTML`<div>User said: ${userInput}</div>`;
console.log(safeHTML);
// '<div>User said: <script>alert("XSS")</script></div>'
// --------------------------------------------
// 8. Highlight Tag
// --------------------------------------------
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] !== undefined ? `**${values[i]}**` : '';
return result + str + value;
}, '');
}
const product = 'JavaScript Book';
const price = 29.99;
const highlighted = highlight`Buy ${product} for only $${price}!`;
console.log(highlighted);
// 'Buy **JavaScript Book** for only $**29.99**!'
// --------------------------------------------
// 9. Currency Formatting Tag
// --------------------------------------------
function currency(strings, ...values) {
return strings.reduce((result, str, i) => {
let value = values[i];
if (typeof value === 'number') {
value = '$' + value.toFixed(2);
}
return result + str + (value !== undefined ? value : '');
}, '');
}
const total = 125.5;
const tax = 10.04;
const formatted = currency`Total: ${total}, Tax: ${tax}, Grand Total: ${
total + tax
}`;
console.log(formatted);
// 'Total: $125.50, Tax: $10.04, Grand Total: $135.54'
// --------------------------------------------
// 10. i18n Tag Example
// --------------------------------------------
const translations = {
'Hello, {0}!': {
es: '¡Hola, {0}!',
fr: 'Bonjour, {0}!',
},
'You have {0} messages': {
es: 'Tienes {0} mensajes',
fr: 'Vous avez {0} messages',
},
};
function i18n(lang) {
return function (strings, ...values) {
// Create key from template
const key = strings.reduce((result, str, i) => {
return result + str + (i < values.length ? `{${i}}` : '');
}, '');
// Get translation or use original
let template = translations[key]?.[lang] || key;
// Replace placeholders
values.forEach((value, i) => {
template = template.replace(`{${i}}`, value);
});
return template;
};
}
const es = i18n('es');
const fr = i18n('fr');
console.log(es`Hello, ${name}!`); // '¡Hola, Alice!'
console.log(fr`Hello, ${name}!`); // 'Bonjour, Alice!'
// --------------------------------------------
// 11. String.raw
// --------------------------------------------
// Normal template literal processes escapes
console.log(`Line1\nLine2`);
// Line1
// Line2
// String.raw keeps literal backslash
console.log(String.raw`Line1\nLine2`);
// Line1\nLine2
// Useful for regex patterns
const regexPattern = String.raw`\d+\.\d+`;
console.log(regexPattern); // '\d+\.\d+'
const regex = new RegExp(regexPattern);
console.log(regex.test('3.14')); // true
// Windows file paths
const filePath = String.raw`C:\Users\name\Documents\file.txt`;
console.log(filePath); // C:\Users\name\Documents\file.txt
// --------------------------------------------
// 12. SQL Query Tag (Parameterized)
// --------------------------------------------
function sql(strings, ...values) {
const query = strings.reduce((result, str, i) => {
return result + str + (i < values.length ? `$${i + 1}` : '');
}, '');
return {
text: query,
values: values,
};
}
const userId = 123;
const status = 'active';
const query = sql`SELECT * FROM users WHERE id = ${userId} AND status = ${status}`;
console.log(query);
// { text: 'SELECT * FROM users WHERE id = $1 AND status = $2', values: [123, 'active'] }
// --------------------------------------------
// 13. Debug Tag
// --------------------------------------------
function debug(strings, ...values) {
const output = strings.reduce((result, str, i) => {
if (i < values.length) {
const value = values[i];
const type = typeof value;
const display = type === 'object' ? JSON.stringify(value) : String(value);
return result + str + `[${type}: ${display}]`;
}
return result + str;
}, '');
console.log('[DEBUG]', output);
return output;
}
const obj = { x: 1, y: 2 };
const arr = [1, 2, 3];
debug`Object: ${obj}, Array: ${arr}, Number: ${42}`;
// [DEBUG] Object: [object: {"x":1,"y":2}], Array: [object: [1,2,3]], Number: [number: 42]
// --------------------------------------------
// 14. CSS-in-JS Style Tag
// --------------------------------------------
function css(strings, ...values) {
const styles = strings.reduce((result, str, i) => {
return result + str + (values[i] !== undefined ? values[i] : '');
}, '');
// Parse CSS and return object
return styles
.split(';')
.filter((s) => s.trim())
.reduce((obj, declaration) => {
const [prop, value] = declaration.split(':').map((s) => s.trim());
if (prop && value) {
// Convert kebab-case to camelCase
const camelProp = prop.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
obj[camelProp] = value;
}
return obj;
}, {});
}
const primaryColor = '#007bff';
const fontSize = 16;
const styles = css`
color: ${primaryColor};
font-size: ${fontSize}px;
padding: 10px;
border-radius: 4px;
`;
console.log(styles);
// { color: '#007bff', fontSize: '16px', padding: '10px', borderRadius: '4px' }
// --------------------------------------------
// 15. Practical: HTML Template Builder
// --------------------------------------------
function buildCard(data) {
const { title, description, imageUrl, tags = [] } = data;
return `
<article class="card">
${imageUrl ? `<img src="${imageUrl}" alt="${title}">` : ''}
<div class="card-body">
<h2>${title}</h2>
<p>${description}</p>
${
tags.length > 0
? `<div class="tags">
${tags.map((tag) => `<span class="tag">${tag}</span>`).join('')}
</div>`
: ''
}
</div>
</article>
`.trim();
}
const card = buildCard({
title: 'JavaScript Mastery',
description: 'Learn modern JavaScript features',
imageUrl: '/images/js.png',
tags: ['programming', 'javascript', 'web'],
});
console.log(card);