Table of contents
1.
Introduction
2.
JavaScript Template Literals
2.1.
Syntax
2.2.
Back-Tics Syntax  
2.3.
Example 1: Basic Usage  
2.4.
Example 2: Embedding Variables  
2.5.
Example 3: Embedding Expressions  
3.
Multiline Strings
3.1.
Example 1: Basic Multi-Line String  
3.2.
Example 2: Multi-Line String with Variables  
3.3.
Comparison with Traditional Strings  
3.4.
Why This is Useful  
4.
Expressions
5.
Tagged Templates
6.
Quotes Inside Strings  
6.1.
Example 1: Using Quotes in Template Literals  
6.2.
Example 2: Mixing Single & Double Quotes  
6.3.
Comparison with Traditional Strings  
6.4.
Why This Matters  
7.
Raw String
8.
Nested Templates
9.
Interpolation  
9.1.
Example 1: Embedding Variables  
9.2.
 Example 2: Embedding Expressions  
9.3.
 Example 3: Embedding Function Calls  
10.
Comparison with Traditional Concatenation  
10.1.
Why Interpolation is Useful  
11.
Frequently Asked Questions
11.1.
What is the main purpose of template literals in JavaScript?
11.2.
How do you write a multiline string using template literals?
11.3.
What is the difference between regular strings and template literals?
12.
Conclusion
Last Updated: Jan 18, 2025
Easy

Template Literals in JavaScript

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Template literals in JavaScript provide an easier way to work with strings. They allow you to include variables and expressions inside strings without needing to use complicated syntax. Template literals are enclosed by backticks (`) instead of regular quotes, and you can use placeholders (${}) to insert values directly into the string.

Template Literals in JavaScript

In this article, we will discuss how to use template literals, their syntax, features like expressions and tagged templates, and various examples to enhance your understanding.

JavaScript Template Literals

Template literals are enclosed by backticks (`) rather than single or double quotes. They provide an easy way to include variables, write multiline strings, and even process strings using functions. Template literals enhance readability and reduce the complexity of concatenating strings with variables.

Syntax

The syntax for template literals is simple. Instead of using quotes, you use backticks:

`Your string goes here`

To embed variables or expressions, you use the ${} syntax inside the backticks:

`Your name is ${name}`

Back-Tics Syntax  

Template literals in JavaScript use back-ticks (`` ` ``) instead of single (`'`) or double (`"`) quotes to define strings. This small change brings a lot of flexibility & power to how you work with strings. Let’s break it down with examples.  

Example 1: Basic Usage  

Let’s take a look how you can create a simple string using back-ticks:  

const message = `Hello, World!`;
console.log(message); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

Hello, World!


In this example, the string `Hello, World!` is wrapped in back-ticks. It looks similar to using single or double quotes, but the real magic happens when you start using the additional features of template literals.  

Example 2: Embedding Variables  

One of the biggest advantages of template literals is the ability to embed variables directly into the string. This is done using the `${}` syntax.  

const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

Hello, Alice!


Here, the variable `name` is embedded inside the string using `${name}`. This makes the code cleaner & easier to read compared to traditional string concatenation.  

Example 3: Embedding Expressions  

You can also embed expressions inside template literals. This means you can perform calculations or call functions directly within the string.  

const a = 5;
const b = 10;
const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

The sum of 5 and 10 is 15.


In this example, the expression `${a + b}` is evaluated & the result is included in the string.  

Multiline Strings

Creating multi-line strings in JavaScript has always been a bit tricky with traditional strings. You would need to use escape characters (`\n`) or concatenate multiple strings. Template literals make this process much simpler by allowing you to write multi-line strings directly.  

Example 1: Basic Multi-Line String  

Let’s discuss how you can create a multi-line string using template literals:  

const poem = `
Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!
`;
console.log(poem);
You can also try this code with Online Javascript Compiler
Run Code


Output:  

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


In this example, the string spans multiple lines, & the line breaks are preserved exactly as written. This is much cleaner than using `\n` or concatenation.  

Example 2: Multi-Line String with Variables  

You can also embed variables or expressions in multi-line strings:  

const name = "Alice";
const message = `
Hello, ${name}!
Welcome to the world of JavaScript.
Here, you can create amazing things.
`;
console.log(message);
You can also try this code with Online Javascript Compiler
Run Code


Output:  

Hello, Alice!
Welcome to the world of JavaScript.
Here, you can create amazing things.


Here, the variable `name` is embedded in the multi-line string, making it dynamic & easy to read.  

Comparison with Traditional Strings  

Let’s see how you would create a multi-line string using traditional methods:  

// Using escape characters
const oldWay = "Roses are red,\nViolets are blue,\nJavaScript is awesome,\nAnd so are you!";
console.log(oldWay);


// Using concatenation
const concatenatedWay = "Roses are red," + "\n" + 
                         "Violets are blue," + "\n" + 
                         "JavaScript is awesome," + "\n" + 
                         "And so are you!";
console.log(concatenatedWay);


While these methods work, they are harder to read & maintain. Template literals provide a cleaner & more intuitive way to handle multi-line strings.  

Why This is Useful  

Multi-line strings are often used for things like:  

- Writing long messages or paragraphs.  
 

- Formatting code templates or HTML snippets.  
 

- Creating readable output for logs or documentation.  
 

With template literals, you can write multi-line strings naturally, without worrying about escape characters or concatenation.  

Expressions

You can include JavaScript expressions inside template literals using ${}. These expressions can be variables, mathematical calculations, or even function calls.

Example

const name = "Alice";
const age = 22;
const message = `My name is ${name} and I am ${age} years old.`;

console.log(message);
You can also try this code with Online Javascript Compiler
Run Code


Output:

My name is Alice and I am 22 years old.


Explanation:
The ${} syntax allows you to embed variables and computations directly within the string.

Tagged Templates

Tagged templates allow you to call a function with a template literal. The function processes the literal and returns the desired output.

Example

function tag(strings, name, age) {
    return `${strings[0]}${name}${strings[1]}${age}${strings[2]}`;
}


const name = "Bob";
const age = 25;
const message = tag`My name is ${name} and I am ${age} years old.`;


console.log(message);
You can also try this code with Online Javascript Compiler
Run Code


Output:

My name is Bob and I am 25 years old.


Explanation:
The tag function receives the template literal as separate parts: a strings array and the interpolated values. This allows for custom formatting or processing of the string.

Quotes Inside Strings  

One common issue with traditional strings in JavaScript is handling quotes. If your string contains single or double quotes, you need to escape them using a backslash (`\`). Template literals solve this problem elegantly by allowing you to include quotes directly without any extra effort.  

Example 1: Using Quotes in Template Literals  

Let’s discuss how you can include quotes inside a template literal:  

const quote = `He said, "JavaScript is awesome!"`;
console.log(quote);
You can also try this code with Online Javascript Compiler
Run Code


Output: 

He said, "JavaScript is awesome!"


In this example, double quotes are included directly inside the string without needing to escape them. This makes the code cleaner & easier to read.  

Example 2: Mixing Single & Double Quotes  

You can also mix single & double quotes inside a template literal without any issues:  

const mixedQuotes = `She said, 'I love coding in JavaScript!' and added, "It's so powerful."`;
console.log(mixedQuotes); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

She said, 'I love coding in JavaScript!' and added, "It's so powerful."


Here, both single & double quotes are used inside the same string. With template literals, you don’t need to worry about escaping them or using alternate quotes.  

Comparison with Traditional Strings  

Let’s compare this with how you would handle quotes in traditional strings:  

// Using single quotes
const singleQuoteString = 'He said, "JavaScript is awesome!"';
console.log(singleQuoteString); 
// Using double quotes
const doubleQuoteString = "She said, 'I love coding in JavaScript!'";
console.log(doubleQuoteString);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

He said, "JavaScript is awesome!"
She said, 'I love coding in JavaScript!'


While this works, it requires you to carefully choose the type of quotes for the string & escape them if necessary. Template literals eliminate this hassle entirely.  

Why This Matters  

Handling quotes inside strings is a common task in programming. With template literals, you can focus on writing your content without worrying about escaping characters. This makes your code more readable & less error-prone. 

Raw String

The String.raw method allows you to get the raw string from a template literal, preserving escape sequences like \n.

Example

const rawString = String.raw`This is a raw string.\nIt does not process escape characters.`;

console.log(rawString);
You can also try this code with Online Javascript Compiler
Run Code


Output:

This is a raw string.\nIt does not process escape characters.


Explanation:
The String.raw method ensures that escape sequences are treated as plain text instead of being processed.

Nested Templates

You can nest one template literal inside another to create complex strings.

Example

const firstName = "Charlie";
const lastName = "Brown";
const fullName = `${firstName} ${lastName}`;
const greeting = `Hello, ${fullName}! Welcome to JavaScript.`;
console.log(greeting);
You can also try this code with Online Javascript Compiler
Run Code


Output:

Hello, Charlie Brown! Welcome to JavaScript.


Explanation:
Here, one template literal (${firstName} ${lastName}) is embedded inside another to create a final message.

Interpolation  

Interpolation is one of the most powerful features of template literals. It allows you to embed variables, expressions, or even function calls directly inside a string. This makes your code more dynamic & easier to read.  

Example 1: Embedding Variables  

Let’s see how you can embed a variable inside a template literal:  

 

const name = "Bob";

const age = 25;

const message = `My name is ${name} and I am ${age} years old.`;

console.log(message); 

Output: 

My name is Bob and I am 25 years old.

 

In this example, the variables `name` & `age` are embedded directly into the string using `${}`. This is much cleaner than traditional concatenation.  

 

 Example 2: Embedding Expressions  

You can also embed expressions inside template literals. This means you can perform calculations or operations directly within the string.  

 

const a = 10;

const b = 20;

const result = `The sum of ${a} and ${b} is ${a + b}.`;

console.log(result); // Output: The sum of 10 and 20 is 30.

 

Here, the expression `${a + b}` is evaluated, & the result is included in the string.  

 

 Example 3: Embedding Function Calls  

You can even call functions inside template literals. This is useful for dynamic content generation.  

 

function greet(name) {

  return `Hello, ${name}!`;

}

 

const user = "Alice";

const greeting = `${greet(user)} How are you today?`;

console.log(greeting);

Output: 

Hello, Alice! How are you today?

 

In this example, the `greet` function is called inside the template literal, & its result is included in the string.  

Comparison with Traditional Concatenation  

Let’s compare interpolation with traditional string concatenation:  

 

const name = "Bob";

const age = 25;

 

// Using concatenation

const oldWay = "My name is " + name + " and I am " + age + " years old.";

console.log(oldWay); 

Output: 

My name is Bob and I am 25 years old.

 

While this works, it’s harder to read & maintain, especially with longer strings or multiple variables. Interpolation makes the code more concise & readable.  

Why Interpolation is Useful  

Interpolation is particularly useful for:  

  • Creating dynamic messages or templates.  
     
  • Building complex strings with variables & expressions.  
     
  • Writing cleaner & more maintainable code.  


With interpolation, you can focus on the content of your string without worrying about concatenation or escaping characters.  

Frequently Asked Questions

What is the main purpose of template literals in JavaScript?

Template literals make string handling easier by allowing multiline strings, variable interpolation, and embedded expressions, all without using complex concatenation techniques.

How do you write a multiline string using template literals?

You can write a multiline string by simply using backticks and placing your text across multiple lines.

What is the difference between regular strings and template literals?

Regular strings use single or double quotes and require concatenation for variables or expressions, while template literals use backticks and ${} for seamless interpolation.

Conclusion

Template literals in JavaScript simplify string handling by enabling features like multiline strings, embedded expressions, and tagged templates. They reduce the complexity of code and enhance readability, making them an essential tool for modern JavaScript development.

Live masterclass