JavaScript – Template Literals

Template literals are string literals which allows you to create multiline strings and string interpolation.

Template literals are new feature in ECMAScript was first introduced in ES6. It is also called template strings.

Before of ES6, template literals were called as template strings.

Template literals are enclosed by backtick(` `) symbol and variable which need to be concatenate should be ($(expression)) format.

Example: Concatenate a string to a variable

<script>
    var tutorialName = "Template Strings";
    var newTutorialName = `Advance JS ${tutorialName}`;
    console.log(newTutorialName);
</script>

#Output
Advance JS Template Strings

Example: Multiline String

<script>
    console.log(`Using template literal 
multiline string`);  
</script>

#Output
Using template literal 
multiline string

A program using template literals to display first and last name together.

<script>
    let firstName   = "Share";
    let lastName    = "Query";

    function fullName(firstName, lastName)
    {
        return `${firstName} ${lastName}`;
    }

    let full_name =  `Hello ${fullName(firstName, lastName)}`;
    document.write(full_name);
</script>

#Output
Hello Share Query

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial