This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

  • 4.1.3 JS String Templates

    Synonyms:
    • Template Literals
    • Template Strings
    • String Templates
    • Back-Tics Syntax

    Back-Tics Syntax

    Template Literals use back-ticks (``) rather than the quotes ("") to define a string:

    Example

    let text = `Hello World!`;

    Try it yourself

    Quotes Inside Strings

    With template literals, you can use both single and double quotes inside a string:

    Example

    let text = `He's often called "Johnny"`;

    Try it yourself

    Multiline Strings

    Template literals allows multiline strings:

    Example

    let text =
    `The quick
    brown fox
    jumps over
    the lazy dog`;

    Try it yourself

    Interpolation

    • Template literals provide an easy way to interpolate variables and expressions into strings.
    • The method is called string interpolation.
    • The syntax is:
    ${...}

    Variable Substitutions

    Template literals allow variables in strings:

    Example

    let firstName = "John";
    let lastName = "Doe";
    
    let text = `Welcome ${firstName}, ${lastName}!`;

    Try it yourself

    Automatic replacing of variables with real values is called string interpolation.

    Expression Substitution

    Template literals allow expressions in strings:

    Example

    let price = 10;
    let VAT = 0.25;
    
    let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;

    Try it yourself

    Automatic replacing of variables with real values is called string interpolation.

    HTML Templates

    Example

    let header = "Templates Literals";
    let tags = ["template literals", "javascript", "es6"];
    
    let html = `<h2>${header}</h2><ul>`;
    for (const x of tags) {
      html += `<li>${x}</li>`;
    }
    
    html += `</ul>`;

    Try it yourself

    Browser Support

    • Template Literals is an ES6 feature (JavaScript 2015).
    • It is supported in all modern browsers:
    Chrome browser Edge browser Firefox browser Safari browser Opera browser
    Chrome Edge Firefox Safari Opera
    Yes Yes Yes Yes Yes

    Template Literals is not supported in Internet Explorer.

    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon