JavaScript Template Literals


In JavaScript template literals can be used to define strings.


Back-Tics Syntax


In Template Literals, back-tics (``) are used, instead of quotation marks to define strings.


let myStr = `Hi There!`;



With template literals, users can:

  • Use both double and single quotation marks in a string

  • 
    let str = `It's a "beautiful" city`;
    
    

  • Multiline Strings

  • 
    let myStr = `Sometimes
    I think it's
    a beautiful
    city.`;
    
    

  • Can easily insert variable and expressions into strings. This is called string interpolation.

  • 
    let myStr1 = "Hello";
    let myStr2 = "World!";
    let myStr = `The two strings above can be combined as ${myStr1} ${myStr2}`;
    
    
    Live Demo!

With template literals, expressions can also be used inside strings.



let num1 = 50;
let num2 = 22;
let myStr = `The sum of the above two numbers is ${num1 + num2}`;

Live Demo!