Open In App

How to use template string literal in ECMAScript 6 ?

Improve
Improve
Like Article
Like
Save
Share
Report

Template literals are a new feature that was introduced in ECMAScript6, which offers a simple method for performing string interpolation and multiline string creation. 

The use of the string literal enables the creation of multiline strings free of backslashes, the addition of any word or phrase to the quote, the insertion of variables, and the use of mathematical formulas between the strings.

Syntax:

`string text`

This Template Literals also can contain placeholders. We can indicate it by the dollar sign and the curly braces.

`string text ${expression} string text`

Let us see how these Template Literals make our life easy through the following examples.

Example 1: Traditional way of using strings with a newline character.

Javascript




const textMessage = "GFG is the\n" +
"best place to learn DS";
console.log(textMessage);


Output:

GFG is the
best place to learn DS

Example 2: Using Template Literals, we can do the same as the above example without using the newline character. We can instead write the text as needed with line breaks.

Javascript




const textMessage = `GFG is the
best place to learn DS`;
console.log(textMessage);


Output:

GFG is the
best place to learn DS

Example 3: We can also surround some of the text inside single quotes and it would be displayed without any issue.

Javascript




const textMessage = `GFG is the
best 'place' to learn DS`;
console.log(textMessage);


Output:

GFG is the
best 'place' to learn DS

We can also add dynamic content inside the template string. This is possible by defining the variable needed inside curly braces with a dollar sign in front of it.

Example 4: In this example, we will display the name inside the string using the template literal.

Javascript




const name = "User";
const message = `Hi ${name}, Welcome to the GeeksForGeeks`;
console.log(message);


Output:

Hi User, Welcome to the GeeksForGeeks


Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads