JavaScript

Template Literals in JavaScript | Explained

JavaScript is a high-level web programming language that provides us with string data type where we can store strings. Strings can be implemented with single quotes or double quotes (‘’ or “”) in JavaScript.

var myString = "Hello World!";

However, the string data type is limited and does not offer many functionalities like a high-level programming language(python, ruby) gives its developers. This problem was solved when JavaScript introduced Template Literals in ES6. Let us see what template literals are in JavaScript in this post.

Template Literals

Template Literals gives us the ability to work with strings with more control and more power over the traditional string data type. Unlike strings, Template Literals use backticks “ rather than single or double quotation marks as shown below:

var myString = `Hello World!`;

Some of the features Template String provide us are:

  • Interpolation: assigning variables and expressions inside a Template Literal.
  • Multiline strings: We don’t need /n to go to another line, we just simply go to another line in Template Literal and the browser knows that it has to show that string on another line.
  • Tagged Templates: It changes the template literal, and then after changing the template literal returns the resultant string. Tagged templates are just like functions with the exception that they are called without the () parenthesis.

Let’s explore these features one by one:

Interpolation

Variables and expressions can be easily interpolated into strings using template literals. Embedding an expression inside the template literal is known as Interpolation. We can achieve interpolation by using the ${someVar} syntax. Let’s see an example:

var myString = `Hello World!`;

console.log(`He said: ${myString}`);

In the above code, we are initializing a variable and accessing it inside a string using the interpolation syntax. And to display the result onto the console, we are using the console.log() method:

Multiline Strings

Another application of the Template Literal is that it gives us the ability to easily manage or write strings in multiple lines. Before Template Literals, it was a bit difficult and tricky as we had to use the backslash inside double quotes to tell the browser that the string should be on the next line. For example:

var myString = "Hello\n"+"World!";

console.log(myString);

In the above code, we initialized a string and used \n to tell the browser that the string after \n should be on the next line.

Now let’s see how we can achieve the same functionality using Template Literal where we will simply write the second string on another line:

var myString = `Hello

World!`;

console.log(myString);

We can see that Template Literals made it very easy for us to write multiline strings and it is more easily readable and understandable.

Tagged Templates

Another powerful feature Template Literals gives us is the Tagged Templates which simply modify a Template String by appending a function name to the beginning of the template string. In simpler words, a tagged template changes the template literal and returns the resultant string.

Tagged templates are defined exactly like a function however when you call a template tag you don’t use the () parenthesis. The syntax for initializing a tag function is given below:

function tagName(literals, ...substitutions) {

// return some string

}

The tag function takes two arguments; the first is the literals which indicate the literal strings and the second is the …substitutions in which the subsequent inputs parsed for each substitution are stored.

Now let us look at an example to implement a tag function:

// Tag Template

function myTagName(myString) {

return myString;

}

// creating tagged template

const output = myTagName`Hello Name`;

// display result

console.log(output);

In the above code, we have created a function that is returning a string. After that, we created a tagged template and then called the above tag template function for which the syntax used is: myTagName`Hello Name` where the myTagName is the template tag and the Hello Name is the template literal. In the end, we displayed the result using the console.log() method:

Let us now look at another example where we will pass literals as well as substitutions to the tag function:

// values

let greet = "Hello!";

let name = "Jhon";

// tag function

function transform(literals, ...substitutions) {

console.log(literals); // ["", " my name is "]

console.log(substitutions); // ["Hello", "Jhon"]

}

// call Tag Literal function

transform`${greet} my name is ${name}`;

In the above code, we first define the transform tag function which takes in two arguments; “literals” that is an array and has static content (“my name is”) while the substitutions rest parameter is also an array having all the tags(greet, name). The output of the above code is shown below:

Conclusion

The standard datatype String provided by JavaScript was not powerful enough hence JavaScript introduced Template Literals in ES6. Template Literals give us more power over strings and are initialized using backticks . In this post, we saw what Template Literals are in JavaScript along with the features Template Literals offer us over the standard JavaScript string.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.