Easy JavaScript Part 9: What are Template Literals?

Dhananjay Kumar / Tuesday, September 26, 2017

In ES6, two types of literals were introduced:

  1. Template Literals for string concatenation and expression embedding in a string
  2. Tagged Template Literals to tag the Template Literal in a function so the literal can be evaluated in the function

Let’s assume that you need to do the string concatenation with a dynamic expression or with the value of a variable. Take a look at the following code:

var foo = 9;
var result = `Result = ${foo}`;
console.log(result);

Here you see you’ll need to embed the value of variable foo in a string literal. In ES6, you can do this using Template Literals, as shown in the code listing above. Template Literals are mainly used for the following purposes:

  • String concatenation
  • To create multi line strings
  • To embed expressions
  • To use string interpolation

In the code above, we are embedding the expression foo in the string result. To use Template Literals:

  1. Template literals are created inside a back-tick (` `) character.  
  2. In Template literals, placeholders are created using the ${expression} symbol. At run time, the expression will be evaluated and replaced in the placeholders.
  3. In template literals, the expression can be embedded using ${expression}. This is also called an expression interpolation.

Using Template literals, let us create some expression interpolation. Consider the following code:

var num1 = 9;
var num2 = 7;
var result = `Result = ${num1 + num2}  and twice of result = ${2 * (num1 + num2)}`;
console.log(result);

To create expression interpolation here, we are using the Template literal. You’ll also notice the string is broken into multiple lines. If required, you can created a nested template also.

 Tagged Template Literals

ES6 allows you to tag template literals, meaning you can parse that inside a function.  So, if you use Tagged Template Literals, JavaScript will not immediately assign them to a variable, and rather parse them in a function. Let’s see an example:

function sayHello() {
 
 
}
const name = "foo";
const country = "India";
const result = `hey ${name} welcome to ${country}`;
console.log(result); 

Now let’s assume that in the sayHello function, you want to pass a template literal, perform some manipulation, and return a result. To do that, you can tag the template literal to function as shown below:

function sayHello() {
 
 
}
const name = "foo";
const country = "India";
const result = sayHello`hey ${name} welcome to ${country}`;
console.log(result);

Here you have tagged the template literal to the function sayHello. In tagged template literals, the function gets the following parameters:

  1. The first parameter is a string array.
  2. The second parameter onwards are interpolated values.

Let us modify the sayHello function to work with these parameters. Consider the code below:

function sayHello(strings, name, country) {
 
    console.log(strings[0]); //hey
    console.log(strings[1]);// welcome to
    console.log(strings[2]); // empty string
    console.log(strings[3]); // undefined
 
}
const name = "foo";
const country = "India";
const result = sayHello`hey ${name} welcome to ${country}`;
console.log(result);

As you can see, all strings of the template literal will be passed as the first parameter of the function.  In the other two parameters (name and country), interpolated values will be passed. So, the name will contain foo and the country will contain India. Now let’s see the code below: 

function sayHello(strings, name, country) {
    var res = '';
    var ctrstring = '';
    if (country == "India") {
        ctrstring = " visit Delhi";
    }
    else if (country == "USA") {
        ctrstring = " visit NY";
    }
    else {
        ctrstring = " visit any where ";
    }
    res = strings[0] + name + strings[1] + country + ctrstring;
    return res;
}
 
const name = "foo";
const country = "India";
const result = sayHello`hey ${name} welcome to ${country}`;
console.log(result); // hey foo welcome to India visit Delhi 

In the above code snippet, we are checking the value of the interpolated parameter country and then creating a new string and returning that.  You will get the expected output, however there is one problem in the above approach: you are mapping all interpolated parameters in named parameters. This could cause problems for the dynamic number of interpolated parameters. This can be solved using JavaScript REST Parameters (learn more about REST Parameters here). So we should rewrite the above code as it appears below: 

function sayHello(strings, ...params) {
    var res = '';
    var ctrstring = '';
    if (country == "India") {
        ctrstring = " visit Delhi";
    }
    else if (params[1] == "USA") {
        ctrstring = " visit NY";
    }
    else {
        ctrstring = " visit any where ";
    }
    res = strings[0] + params[0] + strings[1] + params[1] + ctrstring;
    return res;
}
const name = "foo";
const country = "India";
 
const result = sayHello`hey ${name} welcome to ${country}`;
console.log(result); // hey foo welcome to India visit Delhi 

As you see, you can combine Rest Parameters and Tagged Template Literals for better use cases.

 

Conclusion

ES6 introduced two types of literals, Template Literals for string concatenation and embedding expressions in a string, and Tagged Template Literals to tag Template Literals in a function so the literal can be evaluated in the function. And in this post we covered both of them in-depth!

In the next post of this "Easy JavaScript" series, you will learn about another important concept of JavaScript, so stay tuned. In the meantime, don’t forget to check out Ignite UI, which you can use with HTML5, Angular, React, or ASP.NET MVC to create rich Internet applications.