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:

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:

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

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s