Signup/Sign In

JavaScript Template Literals

Posted in Programming   LAST UPDATED: OCTOBER 21, 2019

    In ES2015, the concept of template strings was introduced, allowing embedded expressions. It also enables multi-line strings and string interpolation with it. In ES6 (EcmaScript 2016) these are now called as Template literals.

    Template literals are enclosed within back-tick(`) character, while normally we use double or single quotes. Using template literals we can define multi-line strings in JavaScript and can also use it for adding placeholder with expression in a string which are then contatenated by the default function. Enough with the theory, let's see the usage of template literals with examples.




    Multi-line Strings

    Template literals can be used to define single line as well as multi-line strings in JavaScript. All we have to do is enclose the multi-line string within back-ticks. For example,

    var myStr = `This is my
        multiline String
        which is amazing`;



    Expression Interpolation

    Template literals provides us with a better and more simpler syntax(syntactic sugar) to enclose expressions in a string which are evaluated by default and concatenated with the string.

    For example, if we have two variables, a and b with some integer value and we have to display their sum and difference in a string, appending the result of sum operation and substraction on the variables a and b.

    There are many ways of doing so, one of those traditional way would be,

    var a = 7;
    var b = 20;
    var result = "The sum is: "+ (a+b) + " and the difference is: " + (a-b);

    In the code above, we have concatenated the result to the result string. Although, this is also very easy, template literals provide another way, following a more modern syntax, using placeholders.

    var a = 7;
    var b = 20;
    var result = `The sum is: ${a+b} and the difference is: ${a-b}`;
    console.log(result);
    

    Output:

    The sum is: 27 and the difference is: -13 

    In the code above, we have used the back ticks to hold the string which has the expressions embedded in the string. The expressions are enclosed using ${...} symbols in a normal string.

    In the code above, notice that within the ${ } there is an expression, a+b and in the second one a-b which are evaluated normally and the value is concatenated to the string.

    When we use the template literal in this way where we specify an expression to be evaluated and concatenated to the string, internally a default function is called, which concatenates the results of the expressions at the same index in the string where the placeholder ${ } is specified with the expression.

    We can define our own tag function too, to explicitly define how the template literals work. We will learn about it at the end.




    Nested Templates

    We can use template literal inside a template expression, which makes it nested templates. Within a backticked template it is simple to allow inner backticks by using them inside a placeholder ${ } within the template.

    Taking example from the official mozilla.org website, if we have some JavaScript code, which generates a CSS class name based on if the screen is large size or not and one more boolean variable, let's say isCollapsed, which will have true value if a particular component is collapsed due to small screen size.

    var myClass = 'header'
    myClass += (isLargeScreen() ?
       '' : isCollapsed ?
         ' icon-expander' : ' icon-collapser');
    

    The above code, will set in myClass the value header if isLargeScreen() function returns true but if it returns false an additional class name icon-expander or icon-collapser gets added to the class.

    The above code will work fine, but the same can be implemented using nested template literal too.

    var myclass = `header ${ isLargeScreen() ? '' :
                            `icon-${isCollapsed ? 'expander' : 'collapser'}` }`;



    Tagged Template

    When we use template literal with placeholder to embed an expression, the default function called simply evaluate the expression and concatenate the result with the string enclosed in back ticks. But we can provide custom specification for the function which operates on the template literal.

    Following is the syntax,

    myTag `${ car } is a ${ type }`

    For the above expression, if we define myTag as a function with 3 arguments, then by default it will get called. Following is the syntax of thre tag function that we can specify with the template literals:

    function template(strings, ...keys)

    Where, strings is an array containing string parts with placeholder ${ } acting as separator and keys will be expressions. Let's write definition for the myTag function specified above.

    function myTag(strings, carExp, typeExp) {
      var str0 = strings[0]; // " is a "
    
      // There is technically a string after
      // the final expression (in our example),
      // but it is empty (""), so disregard.
      // var str1 = strings[1];
    
      var type;
      if (typeExp == 'sedan'){
        type = 'Luxury car';
      } else {
        type = 'economic car';
      }
    
      // We can even return a string built using a template literal
      return `${carExp}${str0}${type}`;
    }
    

    The idea is to understand that we can customize the template literal behaviour as we want.




    Time for an Example

    Below we have compiled all the examples, run, make a few changes, run again to see how this works.




    Conclusion:

    Using template literals is syntactic sugra, or we can say it simplifies or provides a better way of doing things which can be done in many other ways too in JavaScript.

    About the author:
    This is the official profile of the Studytonight content team.
    Tags:JavaScriptJavaScript ES6
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS