What are Template Literals in JavaScript

Read full article on the Infragistics blog

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);

view raw

templi1.js

hosted with ❤ by GitHub

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);

view raw

templi2.js

hosted with ❤ by GitHub

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

Read full article on the Infragistics blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com