• Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
test
Code4Developers

Code4Developers

Code4Developers
  • Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
  • JavaScript

Javascript: What Are Template Literals?

  • Arif Khoja
  • September 30, 2017
  • 3 minute read
JS
Total
0
Shares
0
0
0

ES6 introduced two types of literals: Template Literals and Tagged Template Literals to tag Template Literals. In this post, we cover both of them in depth!

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

Template Literals

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
  • Creating multi-line strings
  • Embedding expressions
  • Using 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 back-tick (`) characters.
  2. In Template Literals, placeholders are created using the ${expression} symbol. At runtime, 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 create 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’s 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 with 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. 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!

 

Arif Khoja
Arif Khoja

Arif Khoja is a Developer. He is a Javascript Enthusiatic who loves logical programming and has first hand experience in building a cutting edge internet product using Angular. He is also an open source freak and keen about learning and sharing. He writes Javascript both frontend and backend. He loves learning and sharing tech all the time. He also has a hands on experience in SEO and writes articles about latest emerging technologies.

Views: 4,614

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to email a link to a friend (Opens in new window) Email
  • Click to print (Opens in new window) Print

Like this:

Like Loading...

Related Posts

Total
0
Shares
Share 0
Tweet 0
Pin it 0

Leave a ReplyCancel reply

Subscribe to Website via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Posts
  • React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    1 year ago
  • Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    2 years ago
  • Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    2 years ago
  • Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    2 years ago
  • Angular Custom Elements: Creating Reusable Components with Angular

    Angular Custom Elements: Creating Reusable Components with Angular

    2 years ago
  • Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    5 years ago
  • How to Build an Inclusive Esports Community

    How to Build an Inclusive Esports Community

    5 years ago
  • Best Digital Icebreakers

    Best Digital Icebreakers

    5 years ago
  • Email alerts when a docker container stopped in AWS ECS CLUSTER

    Email alerts when a docker container stopped in AWS ECS CLUSTER

    5 years ago
  • New Learning Models for Fall 2020

    New Learning Models for Fall 2020

    5 years ago
Subscribe to Website via Email

Enter your email address to subscribe to this website and receive notifications of new posts by email.

Featured Posts
  • javascript 1
    Spread syntax (three dots) in JavaScript
    • March 21, 2018
  • Angular 2
    Angular 6 CRUD – Part 1: Project Setup, Routing, Service
    • May 9, 2018
  • javascript 3
    Local Storage and Session Storage
    • May 22, 2017
  • Angular 4
    Angular 4 Project Structure
    • June 18, 2017
  • AWS 5
    Email alerts when a docker container stopped in AWS ECS CLUSTER
    • July 24, 2020
Code4Developers
Learning is never ending process

Input your search keywords and press Enter.

%d