Skip to main content

JavaScript String Templates

Introduction

JavaScript string templates, also known as template literals, are a powerful feature introduced in ES6 (ECMAScript 2015) that revolutionized how we create strings in JavaScript. Unlike traditional string concatenation with the + operator, template literals allow you to create strings with embedded expressions and support multi-line strings without special escape characters.

In this tutorial, we'll explore how to use template literals to write cleaner, more readable string manipulation code in JavaScript.

Basic Syntax

Template literals are created using backticks (`) instead of single or double quotes:

javascript
// Traditional string
const traditional = "Hello, world!";

// Template literal
const template = `Hello, world!`;

console.log(traditional); // "Hello, world!"
console.log(template); // "Hello, world!"

While this simple example doesn't show any difference in output, the real power comes when we need to include variables or expressions in our strings.

String Interpolation

One of the most powerful features of template literals is string interpolation - the ability to embed expressions directly inside strings using the ${expression} syntax:

javascript
const name = "Sarah";
const age = 28;

// Traditional string concatenation
const greeting1 = "Hello, my name is " + name + " and I am " + age + " years old.";

// Using template literals
const greeting2 = `Hello, my name is ${name} and I am ${age} years old.`;

console.log(greeting1); // "Hello, my name is Sarah and I am 28 years old."
console.log(greeting2); // "Hello, my name is Sarah and I am 28 years old."

The ${expression} placeholder evaluates the expression inside it and converts the result to a string.

Expressions in Template Literals

You can include any valid JavaScript expression inside the ${} syntax, not just variables:

javascript
const price = 19.99;
const taxRate = 0.07;

const totalMessage = `The total price is $${(price * (1 + taxRate)).toFixed(2)}`;

console.log(totalMessage); // "The total price is $21.39"

You can even call functions inside template literals:

javascript
function calculateDiscount(price) {
return price * 0.9; // 10% discount
}

const originalPrice = 50;
const message = `Original price: $${originalPrice}, After discount: $${calculateDiscount(originalPrice)}`;

console.log(message); // "Original price: $50, After discount: $45"

Multi-line Strings

Another great feature of template literals is the ability to create multi-line strings without using special escape characters like \n:

javascript
// Traditional multi-line string
const multiLine1 = "Line 1\n" +
"Line 2\n" +
"Line 3";

// Template literal multi-line string
const multiLine2 = `Line 1
Line 2
Line 3`;

console.log(multiLine1);
// Line 1
// Line 2
// Line 3

console.log(multiLine2);
// Line 1
// Line 2
// Line 3

This makes your code much cleaner when working with large blocks of text.

HTML Templates

Template literals are particularly useful when generating HTML content from JavaScript:

javascript
const user = {
name: 'John Doe',
avatar: 'avatar.jpg',
role: 'Admin'
};

const userCard = `
<div class="user-card">
<img src="${user.avatar}" alt="User Avatar">
<h2>${user.name}</h2>
<span class="badge">${user.role}</span>
</div>
`;

document.body.innerHTML = userCard;

This makes generating dynamic HTML content much more readable compared to traditional string concatenation.

Tagged Templates

Template literals come with an advanced feature called tagged templates, which allows you to parse template literals with a function:

javascript
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
const value = values[i] || '';
return result + string + (value ? `<span class="highlight">${value}</span>` : '');
}, '');
}

const name = "JavaScript";
const version = "ES6";

const result = highlight`Learn ${name} ${version} template literals!`;

console.log(result);
// "Learn <span class="highlight">JavaScript</span> <span class="highlight">ES6</span> template literals!"

Tagged templates are powerful for creating domain-specific languages, internationalization, styling strings, sanitizing input, and more.

Practical Examples

Example 1: Building a URL with Query Parameters

javascript
function buildUrl(baseUrl, params) {
const queryString = Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');

return `${baseUrl}?${queryString}`;
}

const url = buildUrl('https://api.example.com/search', {
query: 'JavaScript templates',
sort: 'relevance',
page: 1
});

console.log(url);
// https://api.example.com/search?query=JavaScript%20templates&sort=relevance&page=1

Example 2: Generating Email Templates

javascript
function createEmailTemplate(user, product) {
return `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h1>Thank you for your purchase, ${user.firstName}!</h1>

<p>We're excited that you chose the ${product.name}.</p>

<div class="order-details">
<p><strong>Order Number:</strong> ${user.orderNumber}</p>
<p><strong>Amount:</strong> $${product.price.toFixed(2)}</p>
</div>

<p>If you have any questions about your order, reply to this email or contact us at [email protected].</p>
</div>
`;
}

const user = {
firstName: 'Alex',
orderNumber: 'ORD-12345'
};

const product = {
name: 'JavaScript Mastery Course',
price: 49.99
};

const emailHTML = createEmailTemplate(user, product);
console.log(emailHTML);

Example 3: Creating SQL Queries

javascript
function createSelectQuery(table, fields, conditions) {
const fieldList = fields.join(', ');
const whereClause = Object.entries(conditions)
.map(([field, value]) => `${field} = '${value}'`)
.join(' AND ');

return `SELECT ${fieldList} FROM ${table} WHERE ${whereClause};`;
}

const query = createSelectQuery(
'users',
['id', 'name', 'email'],
{ status: 'active', role: 'admin' }
);

console.log(query);
// SELECT id, name, email FROM users WHERE status = 'active' AND role = 'admin';

Best Practices

  1. Use template literals for string interpolation: Whenever you need to combine strings with variables, template literals are cleaner than concatenation.

  2. Leverage multi-line capability: For any string that spans multiple lines, template literals improve readability.

  3. Be careful with expressions: Complex expressions inside ${} can make your template harder to read. Consider extracting complex logic to variables or functions.

  4. Use tagged templates for specialized formatting: When you need custom string processing, tagged templates can be very powerful.

  5. Watch for security: When using template literals to generate HTML, be careful about XSS vulnerabilities if user input is involved.

Summary

JavaScript template literals provide a more elegant way to work with strings, offering:

  • String interpolation with ${expression} syntax
  • Multi-line string support without escape characters
  • Tagged templates for advanced string processing

They are especially useful when generating dynamic content like HTML, URLs, SQL queries, and any text that combines static content with dynamic values.

Exercises

  1. Convert the following string concatenation to a template literal:

    javascript
    const product = "laptop";
    const price = 999;
    const message = "The " + product + " costs $" + price + ".";
  2. Create a template function that takes a user object and generates an HTML card with their name, email, and role.

  3. Create a tagged template function that automatically formats numbers as currency when they appear in a string.

  4. Create a SQL query builder that generates INSERT statements using template literals.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)