Home ยป JavaScript Template Literals Tutorial with Examples

JavaScript Template Literals Tutorial with Examples

Template literals (also called template strings) in JavaScript are a powerful feature introduced in ES6 (ECMAScript 2015).

They allow you to create multi-line strings, embed variables and expressions into strings, and make string concatenation easier and more readable.

In this tutorial, you'll learn:

What are template literals?
Basic syntax of template literals
Embedding expressions with template literals
Multi-line strings with template literals
Tagged template literals
Practical examples of template literals in JavaScript

1. What Are Template Literals?

Template literals are string literals that allow embedded expressions. They are enclosed by backticks (`) rather than regular quotes (” or ‘). Template literals provide several key benefits:

Easier string interpolation (inserting variables/expressions directly in strings).
Multi-line string support.
Tagged template literals for more advanced use cases.

2. Basic Syntax of Template Literals

The basic syntax for template literals uses backticks (`) instead of single or double quotes. You can embed expressions inside ${}.

Example 1: Basic Template Literal

let name = "Alice";
let greeting = `Hello, ${name}!`;

console.log(greeting);  //

Output:

 Hello, Alice!

In this example:

The variable name is embedded into the string using ${}.
The string is enclosed in backticks (`), which allows for easier and more readable interpolation.

Example 2: Expression Embedding

You can embed any valid JavaScript expression inside a template literal.

let x = 10;
let y = 20;

let result = `The sum of ${x} and ${y} is ${x + y}.`;
console.log(result);  //

Output:

 The sum of 10 and 20 is 30.

In this example:

The expression ${x + y} evaluates to 30, and the result is inserted into the string.

3. Embedding Expressions with Template Literals

You can embed any type of expression inside a template literal, including variables, function calls, and even ternary operations.

Example 3: Function Call Inside a Template Literal

function getGreeting(name) {
    return `Hello, ${name}!`;
}

let message = `${getGreeting('Bob')}, welcome to the site.`;
console.log(message);  //

Output:

 Hello, Bob!, welcome to the site.

Here, the function getGreeting() is called inside the template literal, and the result is embedded directly into the string.

Example 4: Ternary Operator in Template Literal

let isMember = true;

let welcomeMessage = `Welcome ${isMember ? 'back' : 'to the membership'}!`;
console.log(welcomeMessage);  //

Output:

 Welcome back!

In this example:

A ternary operator is used inside the template literal to decide which part of the string to display based on the isMember variable.

4. Multi-Line Strings with Template Literals

Before ES6, creating multi-line strings required awkward concatenation or escaping newlines. With template literals, you can easily create multi-line strings without using special characters.

Example 5: Multi-Line String

let poem = `Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!`;

console.log(poem);

Output:

Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!

In this example:

The backticks allow the string to span multiple lines naturally, making it easier to write and read multi-line text.

5. Tagged Template Literals

Tagged template literals allow you to call a function (a tag) before the string is processed. This is useful for advanced use cases like escaping user input or custom formatting.

A tagged template literal is written by placing a function name (tag) before the template literal. The tag function receives the literal strings and embedded expressions as arguments.

Example 6: Tagged Template Literal

function highlight(strings, ...values) {
    return strings.map((str, i) => `${str}<strong>${values[i] || ''}</strong>`).join('');
}

let name = "Alice";
let age = 25;

let result = highlight`My name is ${name} and I am ${age} years old.`;
console.log(result);  // <strong>Output:</strong> My name is <strong>Alice</strong> and I am <strong>25</strong> years old.

In this example:

The highlight function is used as a tag. It receives the string parts and embedded expressions, then processes them to add HTML tags around the expressions.
The highlight function customizes how the template literal is outputted.

6. Practical Examples of Template Literals in JavaScript

Example 7: Generating HTML Content

Template literals can be used to generate HTML content dynamically.

let name = "John";
let age = 30;
let job = "Developer";

let htmlContent = `
  <div>
    <h1>${name}</h1>
    <p>Age: ${age}</p>
    <p>Job: ${job}</p>
  </div>
`;

console.log(htmlContent);

Output:

<div>
  <h1>John</h1>
  <p>Age: 30</p>
  <p>Job: Developer</p>
</div>

 

In this example:

Template literals are used to dynamically generate an HTML snippet, making it easy to insert variables into the structure.

Example 8: Logging with Template Literals

Template literals are helpful for creating more readable log messages.

let fileName = "report.pdf";
let fileSize = 1.5; // in MB

console.log(`File ${fileName} is ${fileSize} MB in size.`);

Output:

File report.pdf is 1.5 MB in size.

In this example:

Template literals simplify the construction of the log message by directly embedding variables into the string.

Example 9: Creating SQL Queries with Template Literals

Template literals are useful for building SQL queries dynamically.

let tableName = "users";
let userId = 123;
let query = `SELECT * FROM ${tableName} WHERE id = ${userId};`;

console.log(query);  //

Output:

 SELECT * FROM users WHERE id = 123;

In this example:

A dynamic SQL query is generated using template literals, which makes it easy to insert table names and parameters into the query string.

Conclusion

JavaScript template literals provide a powerful and flexible way to work with strings. They simplify string interpolation, make multi-line strings easier to handle, and offer advanced features like tagged templates. Here's a summary of what you've learned:

Template literals are enclosed in backticks (`) and allow embedded expressions with ${}.
You can use template literals to embed variables, functions, and expressions into strings.
Template literals support multi-line strings without the need for concatenation or escape characters.
Tagged template literals allow you to customize the output of a template literal by passing it through a function.

By using template literals, you can write more concise, readable, and maintainable code in JavaScript!

You may also like