Skip to main content
Course/Module 5/Topic 4 of 5Intermediate

JavaScript Template Literals & String Features

Learn template literals, tagged templates, string methods, and modern string manipulation techniques

35 min•By Priygop Team•Last updated: Feb 2026

Template Literals

Template literals are string literals that allow embedded expressions and multiline strings. They provide a more powerful and flexible way to work with strings compared to traditional string concatenation.

String Features

  • Template Literals: Embedded expressions with ${}
  • Multiline Strings: Natural line breaks
  • Tagged Templates: Custom string processing
  • String Methods: Modern string manipulation
  • Unicode Support: Extended Unicode features
  • String Interpolation: Dynamic content insertion

Template Literal Examples

Example
// Basic template literals
const name = 'John';
const age = 30;
const greeting = `Hello, my name is ${name} and I'm ${age} years old.`;
console.log(greeting); // "Hello, my name is John and I'm 30 years old."

// Multiline strings
const multiline = `
    This is a multiline
    string that spans
    multiple lines
    without needing \n
`;
console.log(multiline);

// Expressions in template literals
const a = 5;
const b = 10;
const calculation = `${a} + ${b} = ${a + b}`;
console.log(calculation); // "5 + 10 = 15"

// Conditional expressions
const isLoggedIn = true;
const message = `Welcome ${isLoggedIn ? 'back' : 'guest'}!`;
console.log(message); // "Welcome back!"

// Function calls
function formatCurrency(amount) {
    return `$${amount.toFixed(2)}`;
}

const price = 29.99;
const formattedPrice = `The price is ${formatCurrency(price)}`;
console.log(formattedPrice); // "The price is $29.99"

// Tagged templates
function highlight(strings, ...values) {
    let result = '';
    strings.forEach((string, i) => {
        result += string;
        if (i < values.length) {
            result += `<span class="highlight">${values[i]}</span>`;
        }
    });
    return result;
}

const highlighted = highlight`Hello ${name}, you are ${age} years old!`;
console.log(highlighted); // "Hello <span class="highlight">John</span>, you are <span class="highlight">30</span> years old!"

// SQL query builder
function sql(strings, ...values) {
    let query = '';
    strings.forEach((string, i) => {
        query += string;
        if (i < values.length) {
            query += `'${values[i]}'`;
        }
    });
    return query;
}

const tableName = 'users';
const columnName = 'name';
const columnValue = 'John';
const sqlQuery = sql`SELECT * FROM ${tableName} WHERE ${columnName} = ${columnValue}`;
console.log(sqlQuery); // "SELECT * FROM 'users' WHERE 'name' = 'John'"

// HTML template builder
function html(strings, ...values) {
    return strings.reduce((result, string, i) => {
        return result + string + (values[i] || '');
    }, '');
}

const title = 'My Page';
const content = 'Welcome to my website!';
const htmlTemplate = html`
    <!DOCTYPE html>
    <html>
        <head>
            <title>${title}</title>
        </head>
        <body>
            <h1>${title}</h1>
            <p>${content}</p>
        </body>
    </html>
`;

// String methods with template literals
const text = 'Hello World';
const upperText = `${text.toUpperCase()}`;
const lowerText = `${text.toLowerCase()}`;
const reversedText = `${text.split('').reverse().join('')}`;

console.log(upperText); // "HELLO WORLD"
console.log(lowerText); // "hello world"
console.log(reversedText); // "dlroW olleH"

// Nested template literals
const user = {
    name: 'Alice',
    preferences: {
        theme: 'dark',
        language: 'en'
    }
};

const userInfo = `
    User: ${user.name}
    Theme: ${user.preferences.theme}
    Language: ${user.preferences.language}
    Status: ${user.active ? 'Active' : 'Inactive'}
`;

// Template literal with conditional rendering
function renderUserCard(user) {
    return `
        <div class="user-card">
            <h2>${user.name}</h2>
            <p>Email: ${user.email}</p>
            ${user.avatar ? `<img src="${user.avatar}" alt="Avatar">` : ''}
            ${user.bio ? `<p>${user.bio}</p>` : ''}
            <div class="actions">
                ${user.isAdmin ? '<button class="admin-btn">Admin Panel</button>' : ''}
                <button class="edit-btn">Edit Profile</button>
            </div>
        </div>
    `;
}

Practice Exercise: Template Literals

Example
// Exercise: Build a Template Engine
class TemplateEngine {
    constructor() {
        this.templates = new Map();
    }
    
    register(name, template) {
        this.templates.set(name, template);
    }
    
    render(templateName, data) {
        const template = this.templates.get(templateName);
        if (!template) {
            throw new Error(`Template '${templateName}' not found`);
        }
        
        return template(data);
    }
    
    // Email template
    createEmailTemplate() {
        return (data) => `
            <!DOCTYPE html>
            <html>
                <head>
                    <title>${data.subject}</title>
                </head>
                <body>
                    <h1>${data.subject}</h1>
                    <p>Dear ${data.recipientName},</p>
                    <p>${data.message}</p>
                    ${data.attachments ? `
                        <h3>Attachments:</h3>
                        <ul>
                            ${data.attachments.map(file => `<li>${file.name} (${file.size})</li>`).join('')}
                        </ul>
                    ` : ''}
                    <p>Best regards,<br>${data.senderName}</p>
                </body>
            </html>
        `;
    }
    
    // Report template
    createReportTemplate() {
        return (data) => `
            <div class="report">
                <h1>${data.title}</h1>
                <p>Generated on: ${new Date().toLocaleDateString()}</p>
                <div class="summary">
                    <h2>Summary</h2>
                    <p>Total Items: ${data.items.length}</p>
                    <p>Total Value: ${data.totalValue.toFixed(2)}</p>
                </div>
                <div class="items">
                    ${data.items.map(item => `
                        <div class="item">
                            <h3>${item.name}</h3>
                            <p>Price: ${item.price.toFixed(2)}</p>
                            <p>Quantity: ${item.quantity}</p>
                            <p>Total: ${(item.price * item.quantity).toFixed(2)}</p>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }
    
    // Notification template
    createNotificationTemplate() {
        return (data) => `
            <div class="notification ${data.type}">
                <div class="icon">${data.icon || 'šŸ“¢'}</div>
                <div class="content">
                    <h3>${data.title}</h3>
                    <p>${data.message}</p>
                    ${data.action ? `
                        <button onclick="${data.action.handler}">
                            ${data.action.text}
                        </button>
                    ` : ''}
                </div>
                ${data.dismissible ? '<button class="close">Ɨ</button>' : ''}
            </div>
        `;
    }
}

// Test the template engine
const engine = new TemplateEngine();

// Register templates
engine.register('email', engine.createEmailTemplate());
engine.register('report', engine.createReportTemplate());
engine.register('notification', engine.createNotificationTemplate());

// Test email template
const emailData = {
    subject: 'Welcome to our platform',
    recipientName: 'John Doe',
    message: 'Thank you for joining our platform. We're excited to have you on board!',
    senderName: 'The Team',
    attachments: [
        { name: 'welcome.pdf', size: '2.5MB' },
        { name: 'guide.docx', size: '1.8MB' }
    ]
};

const emailHtml = engine.render('email', emailData);
console.log('Email template:', emailHtml);

// Test report template
const reportData = {
    title: 'Sales Report - Q1 2024',
    items: [
        { name: 'Product A', price: 100, quantity: 5 },
        { name: 'Product B', price: 150, quantity: 3 },
        { name: 'Product C', price: 75, quantity: 8 }
    ],
    totalValue: 1000
};

const reportHtml = engine.render('report', reportData);
console.log('Report template:', reportHtml);

// Test notification template
const notificationData = {
    type: 'success',
    title: 'Operation Completed',
    message: 'Your data has been successfully saved.',
    icon: 'āœ…',
    dismissible: true,
    action: {
        text: 'View Details',
        handler: 'viewDetails()'
    }
};

const notificationHtml = engine.render('notification', notificationData);
console.log('Notification template:', notificationHtml);
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep