What is the use of Template Literals in Javascript?

Template literals are a new feature introduced in ES6. It provides an easy way to create multiline strings and perform string interpolation. By simply using template literal, we can improve the code readability.

In ES6, we can use a new syntax ${parameter} inside of the back-ticked string. Before ES6 we made use of the ‘+’ operator whenever we wanted to concatenate strings and also when we wanted to use a variable inside a string which is definitely not a recommended method.

In ES5, we have to break strings like the one below.

        
let Name = 'John';
let Role = 'Software Developer';

console.log("Welcome! \n My Name is   "+Name+"\n I am a "+Role);

// Output: My name is John and I am a Software Developer        
    

While in ES6 we can write same code below

        
let Name = 'John';
let Role = 'Software Developer';

console.log(`My name is ${Name} and I am a ${Role}.`); 

// Output: My name is John and I am a Software Developer        
    

Multi-line Strings
ES6 also provides Multi-line Strings. Users can create multi-line strings by using back-ticks(`).

In ES5, we had to use the below approach.

        
let message = 'Hello World,\n', 
              +'Greetings to all,\n',     
              +'Keep Learning and Practicing!',        
    

In ES6, we had to use the below approach.

        
let message = `Hello World,     
                Greetings to all,
                Keep Learning and Practicing!`
        
    

Tagged templates
Tagged templates are one of the more advanced forms of the template literal. Tagged template literals allow us to parse template literals with a function. The first argument of the tag function contains an array having string values, and the remaining arguments are related to the expression.

The writing of tagged literal is similar to the function definition, but the difference occurs when the tagged literals get called. There are no parentheses () required to call a literal.

        
function name(str) {   
 console.log(str);   
}

name `Hello World`; 

// Output : [‘Hello world’]  
        
    

Raw strings
The template literal raw method allows the accessing of raw strings as they were entered. The string.raw() method is used to show the strings without any interpretation of backslashed characters.

        
var rawText = String.raw`Hello \n World \n How are you? `;
console.log(rawText);   
            
// Output :  Hello \n World \n How are you?                
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top