Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to use template string literal in ECMAScript 6 ?

  • Last Updated : 08 Nov, 2021

In this article, we are going to learn about Template literals. There are different kinds of literals in JavaScript, like the Object Literals and Boolean Literals. We also have String Literals which are indicated by single quotes ‘ ‘ or double quotes ” “. 

Starting from ES6 (ECMAScript 6), we have Template Literals which are indicated by the backtick (` `) character. Template literals help us to write clean code. It is also called a Template string.

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 by the following examples.

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

HTML




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

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.

HTML




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

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.

HTML




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

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.

HTML




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

Output:

Hi User, Welcome to the GeeksForGeeks

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!