Sign in
Log inSign up
Template literals in JavaScript(ES6)

Template literals in JavaScript(ES6)

Prabu Subra's photo
Prabu Subra
·Jan 6, 2018

In ES6 String literals are allowed to embedded expressions. it adds multi line strings and string interpolation options for JavaScript programmers

Template literals should be enclosed by the back-tick (` `) character instead of double or single quotes.

Engine:-

String Interpolation:-

  • Process of variable substitutions, expressions evaluation.
function postGreeting(fullname,address){
    let currentDate = new Date();
    let currentHour = currentDate.getHours();
    let message = currentDate<12?"Good Morning":currentDate<17?"Good Afternoon":"Good Evening";
    console.log('${message}! ${fullname}, ${address}. Welcome to Template Literals.');
        //output:- ${message}! ${fullname}, ${address}. Welcome to Template Literals.
    console.log("${message}! ${fullname}, ${address}. Welcome to Template Literals.");
        //output:- ${message}! ${fullname}, ${address}. Welcome to Template Literals.    
        console.log(`${message}! ${fullname}, ${address}. Welcome to Template Literals.`);
        //output:- Good Evening! James Bond, Bangalore. Welcome to Template Literals.
}
postGreeting("James Bond","Bangalore");

In above example, String literals with double and single quotes are not replacing JavaScript variable names with its value, only with back-tick is replacing the variable names with its value.

Expression:-

  • Template literals will evaluate the expressions too.
console.log(`Hello,${new Date().getHours()<12?"Good Morning":new Date().getHours()<17?"Good Afternoon":"Good Evening"}.`);
//output:- Hello,Good Evening.

Tagged template literals:-

  • Passing template literal in to a function.
  • parse the string literals and values.
  • First argument will be always array of strings from template literal which is passed.
  • After first arguments, remaining all are related to expressions value. it can be spread operator(...), which will be an array of expressions value.
function postGreeting(template,arg){
    console.log(template);
        //output:- (2) ["Hello, ", ".", raw: Array(2)]
    console.log(arg);
        //output:- 20
    return `${template[0]}${arg<12?"Good Morning":arg<17?"Good Afternoon":"Good Evening"}${template[1]}`;
}
console.log(postGreeting`Hello, ${new Date().getHours()}.`);
//output:- Hello, Good Evening.

String Raw:-

  • it is add to get strings without processing escape sequences.
String.raw`Addtion of 1 plus 2 is \n ${1+2}`;
   output:- "Addtion of 1 plus 2 is \n 3"
`Addtion of 1 plus 2 is \n ${1+2}`;
   output:- "Addtion of 1 plus 2 is 
             3"

Template literals are simplifying the process of string manipulations like substitutions, replacement, concatenation.

Reference:-