JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

What are Template Literals in JavaScript?

In JavaScript, template literals are one of the ways of creating string literals. They are created by surrounding a string with backtick (`). With the help of template literals, you can perform the following operations very easily:

  1. Creation of Multiline String
  2. String Concatenation
  3. String Interpolation

Note: Template literals are also known as template strings.

How to create a multiline string using template literals?

Before the advent of template literals, escape characters are used to create the multiline string. This approach is tedious, error-prone and makes your code messy.

let message = "This \
is \
a \
multiline \
string.";
console.log(message)

Output

"This is a multiline string."

As you can see, the new line characters are ignored by the JavaScript interpreter. If you want to keep newline characters, then template literals are the most preferred choice. Let's create a multiline string using template literals.

let message = `This 
is
a
multiline
string.`;
console.log(message);

Output

This 
is
a
multiline
string.

How to concatenate string using template literals?

In JavaScript, + operator is used to concatenate string. Concatenating string using + operator has some serious issues. When the string becomes complex, you end up making mistakes, and the code becomes less readable.

let firstName = "Mohit";
let lastName = "Natani";
let city = "Cardiff";
let message = "Hello, I am " + firstName + " " + lastName + ". I live in " + city;
console.log(message); // Hello, I am Mohit Natani. I live in Cardiff.

You can see that there are more chances of making errors. Also, the code is difficult to comprehend. Let's get around this problem using string interpolation.

let firstName = "Mohit";
let lastName = "Natani";
let city = "Cardiff";
let message = `Hello, I am ${firstName} ${lastName}. I live in ${city}`;
console.log(message); // Hello, I am Mohit Natani. I live in Cardiff.

Now, you can see how elegant the code has become. But, you might be thinking what ${} in the above code is. Template literals use placeholders (${}) to replace variables with their respective values at the runtime. Apart from variables, you can also perform arithmetic operations and call a function from the inside of ${}. If you are interested in learning more about ${}, refer to What is ${} in JavaScript?

Recommended Posts